tags:

views:

140

answers:

3

Hi,

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

+4  A: 

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'
Anurag
"children contains an array of plain DOM nodes" this is misleading. `children()` is a jQuery set like anything else. If you use `.eq(3)` instead of `[3]` it would return a jQuery wrapped DOM element as expected. Any jQuery result set, when accessed with `[]` returns a DOM element.
Doug Neiner
Basically `children.eq(index).hasClass("testClass")` is how your answer should be written.
Doug Neiner
@Doug - The statement "contains an array of plain DOM nodes" is not entirely correct. jQuery returns an *array-like* object which contains DOM nodes indexed by number as in an array. Also, correct me if I'm wrong, but wasn't there a time when jQuery did wrap all DOM nodes by default before it dropped wrapping in favor of performance?
Anurag
@Anurag I guess my point was that by signaling out "The `children` method returns..." you make it sound like that method works differently than any jQuery method that does not break the chain. I am not sure about how jQuery used to work, but for the last few years `[index]` returns the DOM node and since 1.1.2 `eq` returns a jQuery result set with the DOM node at that index.
Doug Neiner
Ok, one note on this - if I wanted to test for two separate classes, can I just list them in the search string like: .hasClass("class1 class2") - meaning I just want to check if that element is of either class type?
Anurag
Ok sorry new here, but how do we return jquery-ness on a variable? For instance: var $e1 = children.eq(index); ?? Then does 'e1' still survive as a jquery-capable object, on which I can call hasClass()? Is it just putitng the $ sign before the var name what's doing it here? Thanks
@user291701 - Prefixing the $ sign does absolutely nothing to a variable. It is legal to use a `$` sign anywhere in a variable name in JavaScript. For example, `var $foo = 1`, `var f$oo = 2;` and `var foo$ = 3`, or maybe `var $$$$$ = "hello"` are all valid JavaScript variable names. You can call jQuery methods on an object returned by `eq` because it wraps the resultset element at the given index with jQuery and returns the wrapped object. Read up about in jQuery's docs - [eq](http://api.jquery.com/eq/).
Anurag
Prefixng jQuery wrapped results with $ is just a convention people follow to easily know if the object is a jQuery result and if jQuery methods can be called on it. You can always query an object for the `jquery` property and find out the same, but that's basically getting your code dirty with inner details of jQuery.
Anurag
+2  A: 

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;
Doug Neiner
I think your second answer is what OP is going for.
patrick dw
@patrick Cool. I thought I understood the question, but the code example with it confused me :)
Doug Neiner
A: 

use eq():

if (children.eq(index).hasClass("testClass"))
colinmarc
Will-do, just can I supply multiple class names in hasClass() to test at once? Like .hasClass("pig horse goat") ?