Is there a more efficient way to do the following?
$(this).parent().parent().parent().parent().parent().addClass('finished');
Note that I need the parent
concept, because I have multiple similar items on the page.
Is there a more efficient way to do the following?
$(this).parent().parent().parent().parent().parent().addClass('finished');
Note that I need the parent
concept, because I have multiple similar items on the page.
-
4
parents('anyCssSelector')
– Sourabh Commented May 26, 2013 at 21:47 -
4
Also
.closest(selector)
– Jonathan Lonowski Commented May 26, 2013 at 21:50 -
Whether there is something more efficient depends on why you needed to use this in the first place… What is
this
, and how does your DOM look like? – Bergi Commented May 26, 2013 at 21:53 - 3 Don't worry about efficiency, worry about maintainability. That is a nightmare to write, much less maintain .. consider designing such elements/structure that a mon factor can be employed to do said task simpler. – user2246674 Commented May 26, 2013 at 21:57
-
1
...if you want both character, and putational efficiency, ditch jQuery and write your own function, like:
function up(node, n) { while (node && n--) { node = node.parentNode; } return node;}
Then you can just do$(up(this, 4)).addClass(...
– user1106925 Commented May 26, 2013 at 22:39
3 Answers
Reset to default 3If the goal is to get the Nth parent, you can mix .parents(selector)
with the :eq()
selector, noting that :eq(0)
gets the 1st item:
$(this).parents(':eq(4)').addClass('finished');
If this is something you use a lot, and adding proper selectors isn't an option, you could just create your own method to get what you want as well :
$.fn.parent_num = function(num) {
var elem = [];
this.each(function() {
var el = this;
while(num>0) {
if (el.parentNode) el = el.parentNode;
num--;
}
elem.push(el);
});
return $(elem || this);
};
to be used like :
$(this).parent_num(5).addClass('finished');
FIDDLE
If you have any way to get the element with a CSS selector, you can do this:
$(this).parents('selector');
.parents()