Home > Web Front-end > JS Tutorial > How to find the parent tag in javascript

How to find the parent tag in javascript

青灯夜游
Release: 2021-10-19 17:32:40
Original
7576 people have browsed it

How to find the parent tag in JS: 1. Use the parentNode attribute, the syntax is "child element object.parentNode"; 2. Use the parent() or parents() method in Jquery, the syntax is "child element object.parentNode". parent()" or "child element object.parents()".

How to find the parent tag in javascript

The operating environment of this tutorial: windows7 system, javascript1.8.5&&jquery2.1.1 version, Dell G3 computer.

The methods to find the parent element node are:

1. Native method--parentNode attribute

The parentNode attribute can be returned The parent node of a node.

元素.parentNode //返回元素的第一个父节点
Copy after login

2. Jquery method (remember to import the package)

  • Element.parent() Returns the first element of the element Parent nodes

  • Element.parents() Returns an array containing all parent nodes of the element

There is one below Example:

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
<div><span><a id="a"></a></span></div>
<script src="jquery-2.1.1.min.js"></script>
<script>
    //原生的方法
    document.getElementById(&#39;a&#39;).parentNode //得到<span>节点
    //也可以这么玩
    document.getElementById(&#39;a&#39;).parentNode.parentNode //得到<div>节点
 
    //Jquery的方法  记得导包哦
    $(&#39;#a&#39;).parent();//得到<span>节点
    $(&#39;#a&#39;).parent().parent();//得到<div>节点
    $(&#39;#a&#39;).parents();//得到所有父级节点   <span> ,<div> ,<body> ,<html>
    $(&#39;#a&#39;).parents(&#39;body&#39;);//得到<body>节点
</script>
</body>
</html>
Copy after login

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to find the parent tag in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template