Virge Assault
Virge Assault

Reputation: 1396

Adding an id to a child with jQuery

I have some plugin-generated html that I can't change, and need to add an id to an <a> tag so that I can change it's href link.

HTML

<div id="wpmem_login">
   <form action="www.staging.com/login" method="POST" class="form">
      <fieldset>
         <!--other html fields-->
         <div align="right" class="link-text">
            <a href="www.staging.com/password_reset"> click to reset password</a>
         </div>
         <div align="right" class="link-text">
            <a href="www.staging.com/register"> click to register</a>
      </fieldset>
   </form>
</div>  

(this code is form generated so I had to type from looking at inspect element, so there are more html fields above these two where I commented and any typos there may be really aren't relevant)

I need to change the href link on the second to last field, password reset, without touching the last link that has identical classes. I know I can do this with $("#reset").attr("href", "http://www.staging.com/pwd_reset") once I have an id or selector #reset on that div, but I'm not sure how to get that selector.

I need help adding an id or getting the .attr function to the right link.

Upvotes: 1

Views: 68

Answers (4)

Hemal
Hemal

Reputation: 3760

You can use jQuery's $ endsWith Selector to get your link and then change href

$('a[href$="password_reset"]').attr("href", "http://www.staging.com/pwd_reset");

Upvotes: 0

gaetanoM
gaetanoM

Reputation: 42054

You can select your anchor using the href attribute:

   $('a[href="www.staging.com/password_reset"]').attr("href", "http://www.staging.com/pwd_reset")

After changing the href, to reselect the same element you need to change your jQuery selector to:

$('a[href="http://www.staging.com/pwd_reset"]')

Upvotes: 1

asmithdev
asmithdev

Reputation: 326

Just use the solution in this post https://stackoverflow.com/a/303961/3866019 to select the right link. For you this would be something like:

$('a[href*="password_reset"]')

where *= means 'contains' and then use .attr('id', 'reset') to set it's id.

jQuery Documentation: http://api.jquery.com/attribute-contains-selector/

Upvotes: 0

Mitch VanDuyn
Mitch VanDuyn

Reputation: 2878

$('a[href$="password_reset"]')

In otherwords find the anchor tag which ends with correct url. Jquery allows some pattern matching capability so can hard code as little of url as possible.

Here is an SO that has details on the pattern matching capability in jquery

Select <a> which href ends with some string

Upvotes: 4

Related Questions