Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access child element out of children()?

Tags:

jquery

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

like image 956
user291701 Avatar asked Jun 14 '10 03:06

user291701


People also ask

How do you access children in JavaScript?

You can access the individual child nodes in the collection by using either the item() method on the collection, or by using JavaScript array-style notation. If the element has no element children, then children is an empty list with a length of 0 .

How do you get children of children in jQuery?

jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.


1 Answers

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'
like image 94
Anurag Avatar answered Oct 13 '22 11:10

Anurag