最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - More efficient way to do multiple parents - Stack Overflow

programmeradmin2浏览0评论

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.

Share Improve this question asked May 26, 2013 at 21:47 David542David542 111k206 gold badges571 silver badges1k bronze badges 6
  • 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
 |  Show 1 more ment

3 Answers 3

Reset to default 3

If 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()

发布评论

评论列表(0)

  1. 暂无评论