views:

41

answers:

3

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.

Sorry I'm pretty new to jQuery.

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

THANKSFOR THE HELP! just realised i asked a silly question :P

+1  A: 

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

$j("#tabs", obj).removeClass();
Kaaviar
+1  A: 

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.

gnarf
+2  A: 

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.

jAndy