1

I have a site that uses for example html element id="some_id" several times and I want to change all those elements with jquery, but when I run the jquery code: $("#some_id").attr("href", "new url"); Or for example $("#some_id").text("new text") I only change the first element/object/link.

Like this:

<a id="username">username1</a>
<a id="username">username1</a>

Jquery that edit the first element:

$("#username").text("username2"); 

How do I edit both elements with jquery.

Felipe Sabino
  • 16,519
  • 5
  • 67
  • 110
ganjan
  • 6,443
  • 22
  • 74
  • 126

3 Answers3

2

You can't have duplicate IDs.

Make them a class instead.

<a class="username">username1</a>
<a class="username">username1</a>
$(".username").text("username2");

Or make the IDs unique:

<a id="username_1">username1</a>
<a id="username_2">username1</a>
$('a[id^="username_"]').text("username2");

This one uses the attribute-starts-with-selector[docs] to select <a> elements where the ID begins with username_.

user113716
  • 299,514
  • 60
  • 431
  • 433
0

That's because you can only use an ID once on each page, and only one of your elements is getting selected in the first place. Use a class instead.

Matti Virkkunen
  • 58,926
  • 7
  • 111
  • 152
0

First of all, having two elements with the same id is invalid HTML. Instead, give them both the same class attribute:

<a class="username">username1</a>
<a class="username">username1</a>

Then, use the following JavaScript:

$('.username').text('username2');

However, your code example doesn't match your title, so this won't change the href of the anchor tags, just their text. To change the href of both, call attr as you have in the title of this question.

FishBasketGordo
  • 21,938
  • 4
  • 54
  • 88