In js, you can use the getAttribute method to obtain the id attribute, and the syntax format is "object.getAttribute(id name)". The "getAttribute()" method is a function that has only one parameter (the name of the attribute to be queried) and is called through the element node object.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Just use the getAttribute("id") function to get the id value of the element
After finding the element, we can use the getAttribute() method to get the values of its various attributes Check it out.
getAttribute() method is a function. It has only one parameter - the name of the attribute you intend to query:
However, the getAttribute() method cannot be called through the document object, which is different from other methods we have introduced before. We can only call it through an element node object.
For example, you can combine it with the getElementsByTagName() method to query each
Syntax:
element.getAttribute(attributename)
Example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>document</title> </head> <body> 读取 <a href="dom_obj_attributes.php" target="_blank">Attr 对象</a>. <p id="demo">单击按钮以显示上述链接的目标属性的值</p> <button onclick="myFunction()">点我</button> <script> function myFunction(){ var a=document.getElementsByTagName("a")[0]; document.getElementById("demo").innerHTML=a.getAttribute("target"); } </script> </body> </html>
Effect:
Extended information:
A document is a node tree.
Nodes are divided into different types: element nodes, attribute nodes, text nodes, etc.
The getElementById() method will return an object that corresponds to a specific element node in the document.
The getElementsByTagName() method will return an array of objects, which correspond to a specific element node in the document.
Each of these nodes is an object.
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to get the id attribute in JavaScript. For more information, please follow other related articles on the PHP Chinese website!