Why does Jquery only affect the first div element? [duplicate]

I am using the "replace" function to remove all non-numeric values in a div.

It seems Jquery replace only affects the first element.

Here is my Jquery:

$('#comment').each(function() {
    var thz = $(this);
    var repl = thz.html(thz.html().replace(/\D+/g, ''));

HTML Code:

<a id="comment1" href="#"> c2f?f011. </a>
<a id="comment1" href="#"> c20ff113. </a>
<a id="comment1" href="#"> c201gf76341. </a>


2011 c20ff113. c201gf76341.

The result I want is:

2011 20113 20176341



You have duplicate ids, Which is invalid and also jQuery ID selector(or any other id selector like document.getElementById which internally jQuery uses because element with ids are indexed by most browsers and are meant to be unique) will return only the first one that appears in DOM. Change it to class and see it working:

$('.comment').each(function() { 
     var thz =  $(this); var repl =
     thz.html(thz.html().replace(/\D+/g, '')); 


<a class="comment1" href="#"> c2f?f011. </a> 
<a class="comment1" href="#">c20ff113. </a> 
<a class="comment1" href="#"> c201gf76341. </a>

By the way had your id been like this:-

<a id="comment1" href="#"> c2f?f011. </a> 
<a id="comment2" href="#">c20ff113. </a> 
<a id="comment3" href="#"> c201gf76341. </a>

Starts with Attribute selector will help you (But slow you down literally, since this is an attribute selector and lose the advantage of using IDs).

$('[id^=comment]').each(function() { // While using this better give a container context $('[id^=comment]', 'container').each(function...
    var thz = $(this);
    var repl = thz.html(thz.html().replace(/\D+/g, ''));


Moral: IDs must be unique


ID in a HTML page is supposed to be unique

That is the reason it targets only the first instance of the element found.

Replace the elements with class instead

$('.comment').each(function() {
       // Your code
$('.comment').each(function() { var thz = $(this); var repl = thz.html(thz.html().replace(/\D+/g, '')); });

replace ur element with id comment to a class comment.

If you use ID several times on elements the selector will only pick the first element with that ID.

But when you use class instead, the selector will pick all the element having that class.


If you really don't want to change the html you can use selector by attribute. But as others suggested, using class instead of id is the best option here.



Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.