The difference between parentNode and parentElement

Before understanding the parentNode and parentElement attributes, you must have a certain understanding of the DOM tree. In the DOM document structure, each part of an HTML page is composed of nodes. There are three types of nodes, element nodes, text nodes, and attribute nodes. It can be seen from the figure that attribute nodes belong to the branch of element nodes. Always consider.

parentNode, parentElement

parentNode: As the name implies - the parent node
parentElement: As the name implies - the parent element

Both are the same under normal circumstances, because the node containing the element can only be the element node, there may be a misunderstanding here, some people may wonder whether the text node can contain the element node as the parent node, which is not possible here Yes, the text node is just the text itself, which counts as a node, and the parent node of the text node is directly the element node.
Then let's talk about the special cases of parentNode and parentElement.

 The running results here are the same. Their ancestor elements are all HTML, but let’s try to think about it. One level up, it is the root document, not an element. Let’s take a look at the following code

 The execution code is as follows:

The only difference here comes out, because parentElement is looking for elements, so when the root document is found, an error with a value of null will appear, and parentNode is looking for nodes, of course it can be displayed!

Guess you like

Origin blog.csdn.net/weixin_44786530/article/details/130507153