Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: children() vs child selector ">"

I have a table that has a section similar to the following:

<tr>
    <td> <span class="myclass"></span>
    </td>
<tr>

my $(this) is set to the tr element and I'm trying to access the Span elements that have the "myclass" class set. The following seems to work:

if ($(this).children('td').children('span').is('.myclass')){
    alert('in here');
}

but when trying to use this:

if ($(this).children("td > span").is('.myclass')){

or this:

if ($(this).children("td span").is('.myclass')){

It does not. I thought that either of the above 2 would come up with similar results (albeit through different methods) but apparently not.

What am I missing here?

Thanks!

like image 280
user417918 Avatar asked Apr 21 '11 22:04

user417918


People also ask

What is the difference between FIND and children methods of jQuery?

The find() method traverses the entire Dom whereas the children() method gets the immediate children of the node. The children() method is to get the immediate children of the node.

What is jQuery child function?

jQuery children() Method The 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.

What is the use of parent () and child () method in jQuery?

It is a jQuery Selector used to select all elements that are the direct child of its parent element. Parameter Values: parent: Using this, the parent element will be selected. child: Using this, the direct child element of the specified parent element will be selected.

What is nth child in jQuery?

jQuery :nth-child() Selector The :nth-child() selector in jQuery is used to select all elements that are the nth child, regardless of type, of their parent.


2 Answers

children(selector) will only match those children that match selector. None of tr's children (the tds) can match td > span, as tr has has no span child elements, only tds and td > span !== td.

The documentation is also quite clear about this:

Get the children of each element in the set of matched elements, optionally filtered by a selector.


What you might want instead is .find():

$(this).find("td > span")

It returns all descendants, not just children, that match the selector.

like image 121
Felix Kling Avatar answered Nov 15 '22 16:11

Felix Kling


From the jQuery docs:

"The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree."

I'd recommend using this:

if ($(this).find('.myclass').length){
    alert('in here');
}

Cheers

like image 44
Kevin Ennis Avatar answered Nov 15 '22 17:11

Kevin Ennis