Tusar
Tusar

Reputation: 23

how to replace a particular div tag with a span tag using jsoup

<div class="c45 c45v0">
    <p><span>J</span>oseph DeSimone made a bold move back</p>
</div>

I want to replace <div class="c45 c45v0"> with a <span class="c6 c77">.

<span class="c6 c77">
    <p><span>J</span>oseph DeSimone made a bold move back</p>
</span>

I tried to use below code to replace but i'm unable to replace it. Would anyone please help me to solve this.

if (elements.select("div.c45.c45v0").size()>0) {
    if (!elements.select("div.c45.c45v0").isEmpty()) {
        elements.tagName("span.c6.c77");
    }   
}

Upvotes: 0

Views: 490

Answers (1)

Pshemo
Pshemo

Reputation: 124225

Based on fact that elements is object from which you are selecting div.c45.c45v0 it looks like it is not the searched element, but only containing one so manipulating it doesn't make much sense. Second thing is that you don't wanted to set class attributes via tagName. You need to set tag via tagName but class attribute either via .attr("class", "c6 c77") or via series of addClass (for new classes) and removeClass(for previous classes).

Demo:

String html =
        "<div class=\"c45 c45v0\">\n" +
        "    <p><span>J</span>oseph DeSimone made a bold move back</p>\n" +
        "</div>";

Document doc = Jsoup.parse(html);

//here 'elements' contain only div.c45.c45v0 elements *from* entire document (doc)
Elements elements = doc.select("div.c45.c45v0");
System.out.println(elements);

//now we can manipulate those selected elements
elements.tagName("span");
elements.attr("class", "c6 c77");
System.out.println("---------------");
System.out.println(elements);

Output:

<div class="c45 c45v0"> 
 <p><span>J</span>oseph DeSimone made a bold move back</p> 
</div>
---------------
<span class="c6 c77"> <p><span>J</span>oseph DeSimone made a bold move back</p> </span>

Upvotes: 1

Related Questions