user291701
user291701

Reputation: 39671

How to access child element out of children()?

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

Answers (3)

Anurag
Anurag

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

colinmarc
colinmarc

Reputation: 2471

use eq():

if (children.eq(index).hasClass("testClass"))

Upvotes: 1

Doug Neiner
Doug Neiner

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

Related Questions