If I have this line and I'm wondering if there's better way to do it.
var TheID = $(this).parent().parent().parent().parent().parent().attr('id');
Note that the div for which I'm looking for the ID has class "MyClass", if that can help.
Thanks.
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
jQuery parentsUntil() Method The parentsUntil() method returns all ancestor elements between the selector and stop. An ancestor is a parent, grandparent, great-grandparent, and so on.
The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.
you can also try closest
for get attribute like this :
$(this).closest('div.Myclass').attr('id');
or second way is
$(this).parents('div.Myclass').attr('id')
see here : http://jsfiddle.net/sKqBL/10/
Get all the .parents()
, and use .eq()
...
$(this).parents().eq(5).attr('id');
...or the :eq()
selector...
$(this).parents(':eq(5)').attr('id');
...or make a function...
function up(el, n) {
while(n-- && (el = el.parentNode)) ;
return el;
}
...and use it like this...
up(this, 5).id
What is your definition of better?
//POJS, fastest
var TheID = this.parentNode.parentNode.parentNode.parentNode.parentNode.id;
//jQuery, terse
var TheID = $(this).closest(".MyClass").prop("id");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With