Verificar se elemento contém outro com JavaScript

249d atrás

0 0

O método Node.contains() informa se um element node está contido em outro elemento.

Sintaxe

Sintaxe da função:

Node.contains(otherNode)

Resultado

Retorna true se "otherNode" estiver contido em "Node", ou seja, se "otherNode" for descendente de "Node" ou for o elemento em si. Retorna false caso contrário.

Exemplo

Adicione no seu HTML:

<h1>This is a Heading</h1>

<div>
    <p>This is a paragraph.</p>
</div>

Agora no #JavaScript adicione o seguinte código:

const
    h1 = document.querySelector('h1'),
    div = document.querySelector('div'),
    p = document.querySelector('p');

div.contains(h1); // false
div.contains(p); // true

Referências

Saiba mais sobre esse método em:

Node: contains() method - Web APIs | MDN

The contains() method of the Node interface returns a boolean value indicating whether a node is a descendant of a given node, that is the node itself, one of its direct children (childNodes), one of the children's direct children, and so on.


Comentários (0)

0/512
Link