Riccardo Riccardo - 6 months ago 37
HTML Question

JQuery: Set attribute for nth element by name selector

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
selector, but it not working with prop/attr method.


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
<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>