Home  >  Article  >  Web Front-end  >  How to get HTML elements in JavaScript

How to get HTML elements in JavaScript

青灯夜游
青灯夜游Original
2021-10-25 14:02:413873browse

Acquisition method: 1. Use the getElementById() method of document; 2. Use the getElementByClassName() method of document; 3. Use the getElementByName() method of document.

How to get HTML elements in JavaScript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.

JavaScript gets HTML elements

document’s getElementById() method

    <body>
        <a id="id">a标签</a>
        <script>//document指当前文件,get即得到,Element即元素,ById即通过id;即通过id值获取当前文件中的元素
            var element = document.getElementById("id");
            console.log(element);
        </script>
    </body>

Result:

document’s getElementByClassName() method:

<body>
    <a class="first">a标签</a>
    <a>a标签2</a>
    <script>//ByClassName即通过Class值;即通过class值获取当前文件中的元素,因为可能不止一个,所以得到的为一个数组
        var element = document.getElementsByClassName("first")[0];//此处只获取第一个
        console.log(element);
        var element2 = document.getElementsByTagName("a")[1];//此处只获取第二个
        console.log(element2);
    </script>
</body>

Result:

Document’s getElementByName() method:

<body>
	<form>
		<input type="student" name="gender" id="1"><label for="1">男</label>
		<input type="student" name="gender" id="2"><label for="2">女</label>
	</form>
	<script>//ByName即通过name值;即通过name值获取当前文件中的元素,因为可能不止一个,所以得到的为一个数组
		var element = document.getElementsByName("gender");
		console.log(element[0]);
		console.log(element[1]);
	</script>
</body>

Result:

[Recommended learning: javascript advanced tutorial

The above is the detailed content of How to get HTML 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