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 use:
to specify in which elements context you want so lookup something. Some people prefer this syntax:
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.You can give a second parameter to your selector to precise the context :
If
obj
is an HTML Element, you can use thecontext
parameter tojQuery(selector, 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:
Although, for either example,
#tabs
will be searching for an element with the IDtabs
, 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.