Home > DeveloperSection > Forums > Why does Jquery only affect the first div element?
ben reitman
ben reitman

Total Post:96

Posted on    June-06-2013 3:18 AM

 JQuery JQuery 

 1 Reply(s)
 2542  View(s)
Rate this:
Hi Expert, 

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

Please help,
Thanks in advance. 


Total Post:604

Posted on    June-06-2013 8:32 AM

Hi Expert,

You have duplicate ids, Which is invalid and also jquery ID selector 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="#"> c2fdf011. </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="#"> c2fdf011. </a> 
<a id="comment2" href="#">c20ff113. </a> 
<a id="comment3" href="#"> c201gf76341. </a>
Starts with selector will help you.

$('[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, ''));

Don't want to miss updates? Please click the below button!

Follow MindStick