开发者

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!


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.


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


I explained this here.

The difference is that the first selector is entirely within the children call, whereas the second one isn't.

Therefore, the first one looks for all children of this which also match td > span. (In other words, all { <span>s children of <td>s } (the selector) that are themselves directly children of this)

The second one will find all <td> children of this, then find all of the <span>s in those <td>s.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜