Suppose i have this structure of elements:
<div class="parent">
<div class="something1">
<div class="something2">
<div class="something3">
<div class="something4"></div>
</div>
</div>
</div>
</div>
And code like this:
$(".something4").click(function(){
//i could do it like this...
$(this).parent().parent().parent().parent().parent();
});
But that seems to be stupid, is there a better way to do this?
also i can’t just say $(.parent) because there are many divs like this with class parent in my page.
You could always use
.parentNode(standard JavaScript). It’s generally a bad idea to use class names that coincide with function/variable names from the library you’re using (this goes for any language). Making your class names more unique is a better approach (for instance, “scparent” instead of “parent”, if the name of your application was “Super Calculator” or something). This avoids conflicts such as the one you’re describing.I would caution using
.closest(), simply because you may create a function like this:And it would grab the parent
div‘s in your code just fine, but if down the road you add a table for displaying data, and you run the function through a child element of the table, you will have to create another implementation that selects thetableelement, because that’s what you now want:By using your function
getParentElem()on thetrelement, you’ll end up grabbing thedivwith id=”tableParent”, rather than the actual parent, which is thetableelement. So, unless you’ve delineated your parent classes appropriately all the way through your code (which can be a pain and isn’t always efficient), you may run into problems. Especially if at any point you’re creating elements programmatically, or reading in data from another 3rd-party library or script.Not saying it’s not good to use
.closest()… just pointing out a possible “gotcha”.