Reputation: 39671
I'd like to get the # of immediate children an element has, and then get the class of a child at a particular index. Something like:
var index = 25;
var children = $("#myListElement").children();
if (index < children.length) {
if (children[index].hasClass("testClass")) {
alert("hi!");
}
}
I think the syntax for .children() is ok, but how do I get the indexed element out of them in jquery style?
Thanks
Upvotes: 7
Views: 9077
Reputation: 141859
The children
method returns an array-like object that contains plain DOM nodes. You need to wrap a contained element with jQuery, or retrieve it using the eq(index)
method to be able to use jQuery methods such as hasClass
on it.
if ($(children[index]).hasClass("testClass"))
jQuery does not wrap them by default for obvious performance reasons.
If you're using Firebug, or Chrome/Webkit Developer Tools, you would get an exception when trying to call an undefined method on an object. See example. Make sure you're watching the console output :)
TypeError: Object #<an HTMLLIElement> has no method 'hasClass'
Upvotes: 11
Reputation: 66191
I am sorry, but I found your question somewhat confusing. Is this what you want?
var parent = $("#myitem"),
count = parent.children().length,
index = parent.children(".theClass").index();
That gets the child index of the item with a specific class, no loop needed.
However, if you need the class (But already have the index) then do this:
var parent = $("#myitem"),
count = parent.children().length,
classN = parent.children()[3].className;
Upvotes: 2