jQuery | Get and change link using near by class or Id value

Author - Webner

In one of our projects we are working on, we faced a problem where we wanted to change the HREF attribute value of anchor tag using jQuery. When we inspected the HTML code no unique id, name or class was given to < a href > element.

So how to get hold of it and change its attribute value if adding the name, id etc is not the option?

To solve this we examined HTML and found that one of the parent element of < a href > was having a unique id. So we accessed that and then used jquery ’s: find() method to get to the nested < a href > element. Since find() returns all matching elements so using first() was what we were looking for (the first ahref), and then we modified the HREF.

For Example:

<form class=’abc’>
<div class=’abc1’>
<div class=’abc’>
<a href=”www.google.com”>
</div>
</div>
</form>

Here div with class abc1 is unique so we can do this:

$(".abc1").find('a').first().attr('href',newurl);

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *