Thursday 15 July 2010

javascript - Why does Jquery only affect the first div element? -



javascript - Why does Jquery only affect the first div element? -

this question has reply here:

how can apply jquery function elements same id? 4 answers

i using "replace" function remove non-numeric values in div.

it seems jquery replace affects first element.

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

result:

2011 c20ff113. c201gf76341.

the result want is:

2011 20113 20176341

you have duplicate ids, invalid , jquery id selector(or other id selector document.getelementbyid internally jquery uses because element ids indexed browsers , meant unique) homecoming first 1 appears in dom. alter class , see working:

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

html

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

by way had id been this:-

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

starts attribute selector help (but slow downwards literally, since attribute selector , lose advantage of using ids).

$('[id^=comment]').each(function() { // while using improve give container context $('[id^=comment]', 'container').each(function... var thz = $(this); var repl = thz.html(thz.html().replace(/\d+/g, '')); }); demo

moral: ids must unique

javascript jquery html

No comments:

Post a Comment