Do an jquery .attr("href", "new url") on sevral objects not just one
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.
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_
.
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.
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.
精彩评论