jQuery loop through Child divs
Solution 1
I think your issue lies with the attempt to get the val off the div after you get the attribute $(this).attr("name").val()
. Using .val()
on a div doesn't make sense. If you remove that $(this).attr("name")
returns the name
property off the divs. You can further specify the div's to loop through by using the class selector in your each rather than just div. $(".cat_ch").each(function () {});
This has been shown in various other answers to this question.
Solution 2
$('#ChosenCategory').children('.cat_ch').each(function() {
});
Or
$('#ChosenCategory > .cat_ch').each(function() {
});
JQuery's .children
method and css3 child selector >
will return only the direct children that match the selector, class .cat_ch
in the example.
If you want to search deeper in the DOM tree, that is, include nested elements, use .find
or omit the child selector:
$('#ChosenCategory').find('.cat_ch').each( function(){} )
Or
$('#ChosenCategory .cat_ch').each( function(){} )
Solution 3
$(function(){
var items=$(".cat_ch")
$.each(items,function (index,item) {
alert($(item).attr("name"));
});
});
Working sample : http://jsfiddle.net/GzKHA/
Solution 4
If you only want to target the Divs inside, try
$('#ChosenCategory div').each( function() {...} );
The other answers require specific classes and/or will also process non-divs within your parent div.
Solution 5
function loopOver(obj) { var chl=obj.firstChild; while(chl) { if(chl.nodeType==1) { var isAttr=chl.getAttribute('name'); if(isAttr) { alert(isAttr); } } chl=chl.nextSibling; } } //This is by far the fastest in terms of execution speed!!! var obj=document.getElementById("ChosenCategory"); loopOver(obj);
Make sure to enclose the each `<div>` tag at the end of each!!
levi
brain is not for storing information, it is for thinking. be aware of skeptical regression... you follow the standards and everything goes nice and smooth give me the gist
Updated on October 23, 2020Comments
-
levi over 3 years
<div id="ChosenCategory" class="chosen"> <div class="cat_ch" name="1"> <div class="cat_ch" name="2"> <div class="cat_ch" name="3"> <div class="cat_ch" name="5"> <div class="clear"> </div> </div>
I want to loop though
div.cat_ch
How?This one fails:
$("div").each(function () { alert("FW"); alert($(this).attr("name").val()); });
-
tigertrussell almost 12 yearsBe warned! This will also hit your "clear" div, you can avoid that by doing $('#ChosenCategory div:not(.clear)') instead
-
Stano almost 12 yearsYeah, why don't you then change the selector to
$('#ChosenCategory div.cat_ch')
? -
tigertrussell almost 12 yearsAlthough the OP did have those classes on there, the question was really phrased as "loop through child divs," so I wanted to give an answer that reflected how to loop through child divs regardless of their names. Page layout often changes in the development of an app, and sometimes it's nice to not have to rewrite your javascript just to match different selectors.