How to access a child from children ()?

I would like to get # from the immediate children that the element has, and then get the class of the child element at a specific 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 fine, but how do I get the index element from them in jquery style?

thanks

+7
jquery
source share
3 answers

The children method returns an object that looks like an array that contains simple DOM nodes. You need to wrap the contained element with jQuery or get it using the eq(index) method in order to be able to use jQuery methods such as hasClass .

 if ($(children[index]).hasClass("testClass")) 

jQuery does not wrap them by default for obvious performance reasons.

If you use Firebug or the Chrome / Webkit developer tools, you will get an exception when you try to call the undefined method on an object. See an example . Make sure you watch console output :)

 TypeError: Object #<an HTMLLIElement> has no method 'hasClass' 
+11
source share

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(); 

Gets the child index of an element with a specific class, no loop required.

However, if you need a class (but already have an index), do the following:

 var parent = $("#myitem"), count = parent.children().length, classN = parent.children()[3].className; 
+2
source share

use eq() :

 if (children.eq(index).hasClass("testClass")) 
0
source share

All Articles