Divyaadz
Divyaadz

Reputation: 175

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.

Upvotes: 3

Views: 1687

Answers (2)

Benoit Vanalderweireldt
Benoit Vanalderweireldt

Reputation: 2989

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>

Upvotes: 2

Yassin Hajaj
Yassin Hajaj

Reputation: 21995

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>

Upvotes: 2

Related Questions