jQuery selectors select from an HTML object other

2019-07-30 00:22发布

jQuery selectors select from the document.
How do I select from somewhere else other than root? Say I want to select some children from an HTML object.

For this

function dothis(obj)
{
     $j("#tabs").removeClass();
     $j("#tabs>ul").removeClass();
     $j("#tabs>ul>li>a").each(function()
     {
         var tabNum = $j(this).attr("href").replace("#", "");
         var tabContent = $j("div[id=" + tabNum + "]");
         tabContent.removeClass();
         $(tabContent).before("<br><h1>" +$j(this).text() + "</h1>\n" );
     });
     $j("#tabs>ul").each(function()
     {
         $j(this).empty();//remove Ul links on top

     });
}

I want to reference the selectors from an HTML Object (obj) i passed into as argument, instead of selecting from document.

This works!

$j("#tabs", obj).removeClass();

3条回答
Fickle 薄情
2楼-- · 2019-07-30 00:33

You can use:

$j(obj).find('#tabs')

to specify in which elements context you want so lookup something. Some people prefer this syntax:

$j('#tabs', obj)

which I would not recommend. It internally will convert it to the exact same as I mentioned above (.find()) and secondly, it is harder to read because of a switched order.

查看更多
姐就是有狂的资本
3楼-- · 2019-07-30 00:35

You can give a second parameter to your selector to precise the context :

$j("#tabs", obj).removeClass();
查看更多
做自己的国王
4楼-- · 2019-07-30 00:57

If obj is an HTML Element, you can use the context parameter to jQuery(selector, context)

jQuery( selector, [ context ] )

selector A string containing a selector expression
context A DOM Element, Document, or jQuery to use as context

I.E. $j("#tabs",obj).removeClass()

You can also use the .find() method on a jQuery object to look for children of the matched element, and internally $(selector, context) just calls $(context).find(selector) anyway.

For example:

function dothis(obj) {
  var $obj = $j(obj);
  $obj.find('#tabs').removeClass();
  // ....
}

Although, for either example, #tabs will be searching for an element with the ID tabs, there can only ever be one element with any given ID in the document, you may need to switch to using a class if you want to make this function work in two different contexts.

查看更多
登录 后发表回答