Testing objects for ancestor/descendent relationship in JavaScript or Jquery

后端 未结 3 1441
-上瘾入骨i
-上瘾入骨i 2020-12-09 17:21

I\'m trying to come up with a reusable JS or jQuery function that would allow me to test if one object is a DOM descendant of another.

I\'ve seen a model of testing

相关标签:
3条回答
  • 2020-12-09 17:46

    In jQuery ancestors using jQuery objects I suggested

    if ($(obj1).parents().index($(obj2)) >= 0) {
        // obj1 is a descendant of obj2
    }
    
    0 讨论(0)
  • 2020-12-09 17:51
    a.contains(b)
    

    This is a pure JavaScript solution using Node.contains. The function is inclusive, a.contains(a) evaluates to true.

    There's an edge case in IE9: if b is a text node, contains will always return false.

    0 讨论(0)
  • 2020-12-09 17:58

    Try this:

    $('#foo').filter(function(){
    
       return $(this).parent().is('#foo-parent');
    
    });
    

    So here we are selecting all the foo elements and then filtering only the elements that have the foo-parent as their immediate parent.

    If you are looking to find if the any of the ancestors of the current object comply to the rule, then I guess it should be:

    $('#foo').filter(function(){
    
       return $(this).parents().is('#foo-parent');
    
    });
    
    0 讨论(0)
提交回复
热议问题