Is there such thing as a relative jQuery selector?

2019-03-25 02:57发布

I have a reference to a jquery object with the this variable. I am looking for a way of applying the child selector to the object.

I'm using $(this).find('table > tbody > tr > td'), but what I'm aiming for is something more like $('[Value of $(this) goes here somehow] > table > tbody > tr > td').

I realise that I can do $(this).children('table').children('tbody').children('tr').children('td'), but I was wondering if there was some syntactic sugar I could use here.

3条回答
三岁会撩人
2楼-- · 2019-03-25 03:21

You can start with a child selector (>) when using .find() as well, like this:

$(this).find('> table > tbody > tr > td')

It's an often overlooked use case, but it works just great for what you're after.

查看更多
在下西门庆
3楼-- · 2019-03-25 03:28

As Nick said, you can use find(), or you can use selector context:

$('> table > tbody > tr > td', this)

// Is the equivalent of
$(this).find('> table > tbody > tr > td')
查看更多
地球回转人心会变
4楼-- · 2019-03-25 03:34

An alternative way would be passing a second parameter $('selector', context), which defines a context for search.

By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function.

$( "div.foo" ).click(function() {
    $( "span", this ).addClass( "bar" );
});
查看更多
登录 后发表回答