Existing HTMl Document
<a href="http://google.com">Link</a>
Like to convert it as:
<a href="#" onclick="openFunction('http://google.com')">Link</a>
Using JSoup Java library many fancy parsing can be done. But not able to find clue to add attribute like above requirement. Please help.
To set an attribute have a look at the doc
String html = "<html><head><title>First parse</title></head>"
+ "<body><p>Parsed HTML into a doc.</p><a href=\"http://google.com\">Link</a></body></html>";
Document doc = Jsoup.parse(html);
Elements links = doc.getElementsByTag("a");
for (Element element : links) {
element.attr("onclick", "openFunction('"+element.attr("href")+"')");
element.attr("href", "#");
}
System.out.println(doc.html());
Will change :
<a href="http://google.com">
into
<a href="#" onclick="openFunction('http://google.com')">Link</a>
Use Element#attr. I just used a loop but you can do it however you want.
Document doc = Jsoup.parse("<a href=\"http://google.com\">Link</a>");
for (Element e : doc.getElementsByTag("a")){
if (e.text().equals("Link")){
e.attr("onclick", "openFunction('http://google.com')");
System.out.println(e);
}
}
<a href="http://google.com" onclick="openFunction('http://google.com')">Link</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With