The biggest problem I am having wi开发者_如何学运维th learning jQuery is how I do get the path to a particular element, id, or class in my document? I have Firebug and the Firebug jQuery extensions installed, but I am not seeing a way to determine the full path. Any tips for a n00b?
I think it's not possible with an unique JQuery function... as I found this.
If you have written valid HTML, all you need is the ID itself (the part in the id attribute of your element). If your id is "myID1" the jQuery selector you need is $("#myID1")
assuming you are using $
for jQuery.
If you are talking about traversing the DOM tree to get elements without ID, look into the child selector, the nth-child selector, the function .children(), the :parent selector, the .parents() function, and the .parent() function. All these can help with DOM traversal.
Well, if you're using Firebug, then you can simply look at this when inspecting any elements.
But that is usually used for other things, and using the whole thing is both inefficient and not recommended if used as a jQuery selector.
Do you mean you want to know the parents all the way up? Look at this and this.
If you just need the path of your elemnt you wish to attach jquery too , you will find it as a breadcrumb in the firebug panel after inspecting it.
You would need to set up a custom function to traverse the element's parents using the .parent() and .parents() functions. Here is some info:
http://api.jquery.com/parent/
and
http://api.jquery.com/parents/
You could run a simple script to check for existence and output that to an array or other type of variable.
Pseudo code:
function traverse_path(elementId) {
if($('#' + elementId).parent()) {
traverse_path($('#' + elementId).parent().attr('id'));
return $('#' + elementId).parent().attr('id') + ' > ';
} else {
return null;
}
}
精彩评论