I want to wrap each Element
of my JSouped document. These Elements
are defined according to the presence of the word color
in the value of the property style
.
The document is: <body><span style="color: rgb(37, 163, 73);">Test</span></body>
.
So I have written:
Document jsoup_document_caption = Jsoup.parse("<body><span style=\"color: rgb(37, 163, 73);\">Test</span></body>");
Elements elements = jsoup_document_caption.getElementsByAttributeValueContaining("style", "color");
Elements jsouped_elements = elements.wrap("<div></div>");
String jsouped_caption = jsouped_elements.outerHtml();
Each of the three last lines, when printed, shows: <span style="color: rgb(37, 163, 73);">Test</span>
.
Considering in particular System.out.println(jsouped_caption)
, we can see it hasn't been wrapped. Do you know why? I have carefully read the doc but didn't find any answer: https://jsoup.org/apidocs/org/jsoup/select/Elements.html + https://jsoup.org/cookbook/.
It's the same if I treat Element
by Element
:
Elements elements = jsoup_document_caption.getElementsByAttributeValueContaining("style", "color");
for(Element element : elements) {
System.out.println("Found element:");
System.out.println(element);
Element jsouped_element = element.wrap("<div></div>");
System.out.println("JSouped:");
String jsouped_caption = jsouped_element.outerHtml();
System.out.println(jsouped_caption);
}
After you wrap
an element, the wrap is outside the element itself - it becomes it's parent, so you can do this:
Document jsoup_document_caption = Jsoup.parse("<body><span style=\"color: rgb(37, 163, 73);\">Test</span></body>");
Elements elements = jsoup_document_caption.getElementsByAttributeValueContaining("style", "color");
System.out.println(elements); //outputs your original selection -<span style="color: rgb(37, 163, 73);">Test</span>
elements.wrap("<div/></div>");
System.out.println(elements); //still the same output - elements is unchanged
Element wrapped = elements.parents().first(); //now you have the original element AND the wrap
System.out.println(wrapped);
The output of the last print is <div>
<span style="color: rgb(37, 163, 73);">Test</span>
</div>