-2

Having a set of "a" tag with the same name:

<a name="link" href="http://link1">
<a name="link" href="http://link2">
<a name="link" href="http://link3">

I need to change the href attribute for the third element with $("['name=link']") selector, but is not working with prop/attr method.

Rick
  • 1,042
  • 2
  • 14
  • 34

1 Answers1

4

I'm trying to understand your question.

By your explanation, I suggest you to try to use ":eq" jQuery Selector. The code'll be something like this:

// eq takes element by index (from 0 to *) in the same 'root' of nodes in DOM structure
$("a[name='link']:eq(2)").attr('href', '__new value__');

Here's the official jQuery documentation to this feature: https://api.jquery.com/eq-selector/

Working example:

$(document).ready(function() {
  $("a[name='link']:eq(2)").attr('href', '__new value__');

  // checking the href value in the console
  console.log($("a[name='link']:eq(2)").attr('href'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a name="link" href="http://link1">1st link</a>
<a name="link" href="http://link2">2nd link</a>
<a name="link" href="http://link3">3rd link</a>
RPichioli
  • 3,245
  • 2
  • 25
  • 29