Home » Java » jsoup – how to append a tag inside an html using java-Exceptionshub

jsoup – how to append a tag inside an html using java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have an HTML

<h1><a>Hello I am html</a></h1>

what I want to achieve –

<h1><a>Hello I am <strong>html</strong></a></h1>

my code:-

Document document = Jsoup.parse(HTML);

Element element = getElementUsingXpath(); // this is working fine 

String originalText = element.text();

String changedText = originalText.substring(0, 6 + 1)
                    + "<strong>"
                    + originalText.substring(6 + 1) +"</strong>";

element.text(changedText)

But I am getting this

Hello I am <strong>html</strong> //this is wrong

I was expecting it to be

Hello I am html

How to&Answers:

the problem got solved with the below code… suggested by @OHGODSPIDERS

Document document = Jsoup.parse(HTML);

Element element = getElementUsingXpath(); // this is working fine 

String originalText = element.text();

String changedText = originalText.substring(0, 6 + 1)
                    + "<strong>"
                    + originalText.substring(6 + 1) +"</strong>";

element.html(changedText)

Answer:

I wanted to show another way of doing this, that uses the TextNode.splitText(offset) method. It’s not really any simpler that Deepak’s answer, but the method could be handy in other circumstances.

splitText splits a text node into two nodes at the specified string offset. After splitting, the node will contain the original text up to the offset, and will have a new text node sibling containing the text after the offset, which is returned.

Document doc = Jsoup.parse("<h1><a>Hello I am html</strong></h1>");
Element el = doc.selectFirst("a");
TextNode textNode = (TextNode) el.childNode(0);
textNode.splitText(textNode.text().indexOf("html")).wrap("<strong>");
System.out.println(doc.body().html());

See the docs for TextNode#splitText(int) and Node#wrap(html).