Code
Code

Reputation: 2129

Changing link of <li> without id

I have a dropdown that does not have an id - I am attempting to change the href value of the a nested in the li via JavaScript or jQuery. This is the markup:

<ul class="dropdown-menu" aria-labelledby="user_info_dropdown" role="menu">  
   <li>
      <a href="myLink.com?id=12431312sdfs2143123"></a> 
   </li> 
</ul>

I am wanting to change the link in the anchor tag to myLink.com?id=12431312sdfs2143123&anotherValue

What is the best way to accomplish this?

Upvotes: 0

Views: 81

Answers (1)

Rion Williams
Rion Williams

Reputation: 76597

There are a variety of ways that you could target this element.

Use the Parent

Since your element is the only element within an list, you could use that from it's target to resolve it :

// This should find it and replace it
$('.dropdown-menu ul li:first a').attr('href','...');

Use an Attribute

If you know exactly what a specific value that needs to be replaced is (i.e. the href attribute), you could use jQuery's attribute selectors to find an element with the appropriate contents and update them :

// Find a link with a specific URL and update it
$('a[href="myLink.com?id=12431312sdfs2143123"]').attr('href','...');

Broader Strokes

If you didn't know the exact href value that you were targeting, you could apply a more generic approach. That is, replace any <a> tags that start with "myLink.com?" and append your querystring value :

$('a[href^="myLink.com?"]').each(function(){
     $(this).attr('href',$(this).attr('href') + '&anotherValue';
});

Upvotes: 2

Related Questions