Jquery.each only works with the first element

I'm having trouble understanding jqueries.each. I have the following code:

$('#testDiv').each(function(index, domEle){ $(this).text(index); }); 

and the following HTML

 <div id="p18"> <div class="inner"> <span>...</span> <p class="right">...</p> <div id="testDiv"></div> </div> </div> <div id="p19"> <div class="inner"> <span>...</span> <p class="right">...</p> <div id="testDiv"></div> </div> </div> <div id="p20"> <div class="inner"> <span>...</span> <p class="right">...</p> <div id="testDiv"></div> </div> </div> 

When the script runs, it only works for the first testDiv, since it sets the text correctly to 0, but the other testDivs.

My common goal is to write a script that sets the div height based on a different div height. The height is different, so I think the loop structure is the way to go (if I'm not mistaken?)

What am I doing wrong with jq code?

+6
source share
5 answers

You cannot use the same #id for different elements. Try renaming the rest and you will get the desired result.

Or do it (works without adding any classes - cleaner code)

 $('.inner div').each(function(index, domEle){ $(this).text(index); }); 
+16
source
Selector

id returns a maximum of one element.

You should never have more than one item with the same identifier. this is invalid HTML

This will work, but you should fix the HTML instead:

 $('div[id="testDiv"]')... 

What you really have to do:

 <div id="p18"> <div class="inner"> <span>...</span> <p class="right">...</p> <div class="testDiv"></div> </div> </div> <div id="p19"> <div class="inner"> <span>...</span> <p class="right">...</p> <div class="testDiv"></div> </div> </div> 

Then select a class:

 $('.testDiv')... 
+6
source

This is not a problem with the each method. You specified the same id for several elements that are not supported.

Use a class instead and you can find all the elements.

Demo: http://jsfiddle.net/Guffa/xaL4n/

+3
source

You have invalid html. Identifiers must be unique. You must change id="testDiv" to class="testDiv"

HTML

 <div id="p20"> <div class="inner"> <span>...</span> <p class="right">...</p> <div class="testDiv"></div> </div> </div> 

Javascript

 $('.testDiv').each(function(index, domEle){ $(this).text(index); }); 
+1
source

You cannot specify the same div id on the html page.

 <div id="testDiv"></div> 

enter

 <div class="testDiv"></div> 

and your function should look like

 $('.testDiv').each(function(index, domEle){ $(this).text(index); 

});

+1
source

Source: https://habr.com/ru/post/917632/


All Articles