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()".
The operating environment of this tutorial: windows7 system, javascript1.8.5&&jquery2.1.1 version, Dell G3 computer.
1. Native method--parentNode attribute
The parentNode attribute can be returned The parent node of a node.
元素.parentNode //返回元素的第一个父节点
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('a').parentNode //得到<span>节点 //也可以这么玩 document.getElementById('a').parentNode.parentNode //得到<div>节点 //Jquery的方法 记得导包哦 $('#a').parent();//得到<span>节点 $('#a').parent().parent();//得到<div>节点 $('#a').parents();//得到所有父级节点 <span> ,<div> ,<body> ,<html> $('#a').parents('body');//得到<body>节点 </script> </body> </html>
[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!