Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSoup - Add onclick function to the anchor href

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.

like image 304
Divyaadz Avatar asked Nov 26 '25 04:11

Divyaadz


2 Answers

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>
like image 77
Benoit Vanalderweireldt Avatar answered Nov 27 '25 18:11

Benoit Vanalderweireldt


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);
    }
}

Output

<a href="http://google.com" onclick="openFunction('http://google.com')">Link</a>
like image 43
Yassin Hajaj Avatar answered Nov 27 '25 16:11

Yassin Hajaj