开发者

jQuery selectors select from an HTML object other than from document root?

开发者 https://www.devze.com 2023-01-02 15:56 出处:网络
jQuery selectors select from the document. How do I 开发者_运维问答select from somewhere else other than root?

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();


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

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


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.


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.

0

精彩评论

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