Javascript dom contains element

Javascript DOM Element Check if element contains another element

Find out if a element is a descendant of a element:

let span = document.getElementById("mySPAN"); let div = document.getElementById("myDIV").contains(span);
!DOCTYPE html> html> head> style> #myDIV !-- w w w .d e mo 2 s . c o m--> border: 1px solid black; >  body> div id="myDIV"> p>I am a p element inside div, and I have a span id="mySPAN">b> span   element inside of me.  p>Click the button to find out if the div element contains a span element. button onclick="myFunction()">Test p id="demo">  script> function myFunction() < let span = document.getElementById("mySPAN"); let div = document.getElementById("myDIV").contains(span); document.getElementById("demo").innerHTML = div; >   

Description

The contains() method returns a Boolean value indicating whether a node is a descendant of a specified node.

A descendant can be a child, grandchild, great-grandchild, and so on.

Browser Compatibility

Syntax

Parameter Values

Parameter Type/Optional Description
node Required. the node that may be contained by a descendant of a specified node

Return Value

A Boolean, indicating whether a node is a descendant of a specified node:

  • Javascript DOM Element append Child element
  • Javascript DOM Element clone Node
  • Javascript DOM Element compare Document Position
  • Javascript DOM Element Check if element contains another element
  • Javascript DOM Element Check if element has a certain Attribute
  • Javascript DOM Element Check if element has Child Nodes
  • Javascript DOM Element insert Adjacent Element

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Node: contains() method

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.

Note: A node is contained inside itself.

Syntax

Parameters

Note: otherNode is not optional, but can be set to null .

Return value

A boolean value that is true if otherNode is contained in the node, false if not.

If the otherNode parameter is null , contains() always returns false .

Example

This function checks to see if an element is in the page’s body. As contains is inclusive and determining if the body contains itself isn’t the intention of isInPage this case explicitly returns false .

function isInPage(node)  return node === document.body ? false : document.body.contains(node); > 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Методы contains и compareDocumentPosition

Материал на этой странице устарел, поэтому скрыт из оглавления сайта.

Если есть два элемента, то иногда бывает нужно понять, лежит ли один из них выше другого, то есть является ли его предком.

Обычные поисковые методы здесь не дают ответа, но есть два специальных. Они используются редко, но когда подобная задача встаёт, то знание метода может сэкономить много строк кода.

Метод contains для проверки на вложенность

var result = parent.contains(child);

Возвращает true , если parent содержит child или parent == child .

Метод compareDocumentPosition для порядка узлов

Метод compareDocumentPosition – более мощный, чем contains , он предоставляет одновременно информацию и о содержании и об относительном порядке элементов.

var result = nodeA.compareDocumentPosition(nodeB);

Возвращаемое значение – битовая маска (см. Побитовые операторы), биты в которой означают следующее:

Биты Число Значение
000000 0 nodeA и nodeB — один и тот же узел
000001 1 Узлы в разных документах (или один из них не в документе)
000010 2 nodeB предшествует nodeA (в порядке обхода документа)
000100 4 nodeA предшествует nodeB
001000 8 nodeB содержит nodeA
010000 16 nodeA содержит nodeB
100000 32 Зарезервировано для браузера

Понятие «предшествует» – означает не только «предыдущий сосед при общем родителе», но и имеет более общий смысл: «раньше встречается в порядке прямого обхода дерева документа.

Могут быть и сочетания битов. Примеры реальных значений:

Источник

HTML DOM Element contains()

The contains() method returns true if a node is a descendant of a node.

The contains() method returns false if not.

Note

A descendant can be a child, grandchild, great-grandchild, .

Syntax

Parameters

Return Value

Browser Support

element.contains() is a DOM Level 1 (1998) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Читайте также:  Setting Font Size
Оцените статью