Talking about the parent node and child node of html element of js

  • 2021-07-09 06:43:01
  • OfStack

parentNode and parentElement have one function, childNodes and children have one function. However, parentNode and childNodes are in line with W3C standards, which can be said to be relatively common. The other two are only supported by IE, not standard, but not supported by Firefox

Example:

"parentNode" is often used to get the parent node of an element. parentNodes is understood as a container, in which there are child nodes, as follows:


<div id="parent">
<b id="child">My text</b>
</div>

In the above code, you see "daddy" as an div container with a "child" in it, which is the bold text part. If you are going to use the getElementById () method to get the bold element and want to know who its "daddy" is, the information returned will be an div. Demonstrate the following script:


<script type="text/javascript">
<!--

alert(document.getElementById"child").parentNode.nodeName);

//-->
</script>

With parentNode, only one "father" can be found, and "son" can also become "father", such as the following example...


<div id="parent">
<div id="childparent">
<b id="child">My text</b>
</div>
</div>

There are two "dads" and two "children" in the above code. The first div (id "parent") is the "dad" of the second div (childparent). There is a bold element in "childparent" (id "child"), which is the "child" of "childparent" div. So, how do you access "Grandpa" (id "parent")? As follows:


<script type="text/javascript">
<!--

alert(document.getElementById("child").parentNode.parentNode.nodeName);


//-->
</script>

Notice that two parentNode are used together? "parentNode. parentNode". The first parentNode is div (id "childparent"), because we want to get the outermost parent element, so we add another parentNode to get div (id "parent").

Use parentNode not only to find an element's nodeName, but also more. For example, you can get a parent node that contains a large number of elements and add a new node at the end. IE has its own name "parentElement", and it is recommended to use parentNode for cross-browser scripts


Related articles: