Home > Article > Web Front-end > How to get page elements through id attribute in javascript
In JavaScript, you can use the getElementById method to obtain page elements. The syntax format is "document.getElementById("id name")". The getElementById method returns a reference to the first object with the specified ID.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Web pages organize information by tags, and the id attribute value of the tag is unique. How to find the element to be obtained through javascript
document.getElementById("id") //语法
Through the following code, it is found that the running result is null or [object HTMLParagraphElement]
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>通过ID获取元素</title> <script type="text/javascript"> var myceshi=document.getElementById('ceshi');//获取元素存储在变量中 // document.write('结果:'+myceshi);//输出变量 alert(myceshi); document.write('结果:'+myceshi);//输出变量 </script> </head> <body> <div id="ceshi">I love javascript</div> <!-- <script type="text/javascript"> var myceshi=document.getElementById('ceshi');//获取元素存储在变量中 // document.write('结果:'+myceshi);//输出变量 alert(myceshi); document.write('结果:'+myceshi);//输出变量 </script> --> </body> </html>
The obtained element is an object. If we want to operate on the element, we have to use its properties or methods. (object HTMLParagraphElement is the object HTML paragraph element. What is obtained is the element. This element is also the object. The obtained object will not display the value inside, so the object HTMLParagraphElement is displayed. If you want to extract the value inside, use innerHTML to obtain)
The getElementById() method returns a reference to the first object with the specified ID.
Defines multiple methods to find elements, in addition to getElementById(), there are also getElementsByName() and getElementsByTagName().
However, if you need to find a specific element in the document, the most efficient method is getElementById().
When manipulating a specific element of the document, it is best to give the element an id attribute, giving it a unique name (in the document), and then you can use that ID to find the desired element.
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to get page elements through id attribute in javascript. For more information, please follow other related articles on the PHP Chinese website!