Deepak
Deepak

Reputation: 370

How to replace a tag using jsoup

I want to replace all image tags with div tag. I am able to select all tags and I know that I have to use replaceWith. But I am unable to use it.

And if I use TextNode for replacing it with <div> </div> and it converts into &amp;lt;div&amp;gt; my div &amp;lt;/div&amp;gt;

I know &amp;lt; and &amp;gt; is for < and >

Please help me.

Upvotes: 4

Views: 14189

Answers (3)

user12347242
user12347242

Reputation:

just use find method and pass specific tags let tag = soup.find('tag_name') tag.name = 'new_tag';//replaced tag

for multiple tag just put inside loop let tag = soup.findAll('tag_name'); if (tag) { for (let i = 0; i < tag.length; i++) { tag[i].name = 'your_new_tag'; } }

Upvotes: 0

neeraj kumar
neeraj kumar

Reputation: 31

This is the simplest way of achieving this:

 Elements elements= doc.getElementsByTag("img");
 elements.tagName("div");

Hope that is working for you.

Upvotes: 3

Hauke Ingmar Schmidt
Hauke Ingmar Schmidt

Reputation: 11607

I guess you are replacing with element.replaceWith(new TextNode("<div></div>"),"");?

A Textnode is for text and escapes content - thats why you see the HTML entities. You need to replace with a tag, so do something like element.replaceWith(new Element(Tag.valueOf("div"), ""));.

Upvotes: 13

Related Questions