Home>Article>Web Front-end> What are the ways to get elements in JavaScript?

What are the ways to get elements in JavaScript?

醉折花枝作酒筹
醉折花枝作酒筹 Original
2021-07-16 11:37:15 18626browse

The methods of getting elements in JavaScript are: 1. Get elements based on id; 2. Get elements based on tag names; 3. Get elements based on the value of the name attribute; 4. Get elements based on the name of the class style; 5. , Get elements based on the selector.

What are the ways to get elements in JavaScript?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

1. Get the element based on the id

document.getElementById("value of the id attribute");

2. Get the element based on the tag name

document .getElementsByTagName("The name of the tag");

3. Get the element based on the value of the name attribute

document.getElementsByName("The value of the name attribute");

4 .Get elements based on the name of the class style

document.getElementsByClassName("Name of the class style");

5.Get elements based on the selector

1.document.querySelector ("selector");

2.document.querySelectorAll("selector");

1. Get elements based on id

document.getElementById("id attribute The value of .getElementsByTagName("name of tag");

The return value is a pseudo array

Case: Click the button to change the text content of multiple p tags

   

3.According to Get the value of the name attribute of the element

document.getElementsByName("the value of the name attribute");

The return value is a pseudo array

Case:Case:Click the button to change The value attribute value in all text boxes whose name attribute value is name1

  

哈哈,我又变帅了

哈哈,我又变帅了

哈哈,我又变帅了

哈哈,我又变帅了

哈哈,我又变帅了

4. Get elements based on the name of the class style

document.getElementsByClassName("Name of the class style") ;

The return value is a pseudo array


Case: Modify the values of all text boxes

 






5. Get elements based on the selector

1.document.querySelector( "Selector");

The return value is an element object

Case: Click the button pop-up box

 


2.document.querySelectorAll("Selector");


The return value is a pseudo array

Case: modify the values of all text boxes

    

[Recommended learning:

javascript advanced tutorial

]

The above is the detailed content of What are the ways to get elements in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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