Q:

JSoup Getting Text Without Wrapping Tag Under an Element

How do I get the following 'Some random text', and wrap it with a span?
e.g. I have the following element :
<div>
    Some random text 1
    <a href="some_url">Go to Link</a>
</div>
<div>
    <span>Some random text 2</span>
    <a href="some_url">Go to Link</a>
</div>

And I would have something like this :
<div>
    <span>Some random text 1</span>
    <a href="some_url">Go to Link</a>
</div>
<div>
    <span>Some random text 2</span>
    <a href="some_url">Go to Link</a>
</div>

You see, some divs are already wrapped with span, and some aren't. I want to wrap only those that haven't been wrapped.

A:

This quick solution may help you. I tested it using jsoup v1.12.1
Firstly find all elements by div tag, without the span:
   List<Element> elements = jsoupDocument
            .getElementsByTag("div")
            .stream()
            .filter(div -> div.getElementsByTag("span").isEmpty())
            .collect(Collectors.toList());

Then iterate through found elements and update them wrapping its text within span tag:
    elements.forEach(div -> {
        // dissect element
        String text = div.ownText();
        Elements children = div.children();

        // clear any existing inner HTML and replace it with an empty String.
        div.text("");

        // put all elements back together and wrap the div text with the span tag
        div.prepend(String.format("<span>%s</span>", text));
        children.forEach(div::appendChild);
    });

    LOG.info(jsoupDocument.toString());

