Check if div is descendant of another

后端 未结 4 610
灰色年华
灰色年华 2020-12-13 18:04

Best way to find out if element is a descendant of another there is another question, very similiar to this one but its jquery.

so, how do I do it in js ? I have di

相关标签:
4条回答
  • 2020-12-13 18:30

    If you want to use pure javascript use node.contains.

    e.g.

    var a = document.getElementById('a');
    var d = document.getElementById('d')
    if (a.contains(d)) {
        alert('d is a child of a');
    }
    

    Fiddle: http://jsfiddle.net/FlameTrap/pwVPC/

    0 讨论(0)
  • 2020-12-13 18:45

    The method closest() might also be useful in such cases. This method returns the closest ancestor element of an element that matches a given selector (e.g. a class or id). If there is no such element, the method returns null.

    let d = document.getElementById("d");
    // if there is no ancestor with the id 'a', the method returns null and this evaluates to false:
    if(d.closest("#a")){
       alert("d is a descendant of an element with the id 'a'");
    }
    

    You can find further description and more usage examples on MDN.

    0 讨论(0)
  • 2020-12-13 18:51
    // x is the element we are checking
    while (x = x.parentNode) { 
        if (x.id == "a") console.log("FOUND");
    }
    
    0 讨论(0)
  • 2020-12-13 18:53

    You can use node.contains to check if a node contains another node. https://developer.mozilla.org/en-US/docs/Web/API/Node.contains

    0 讨论(0)
提交回复
热议问题