Home > Web Front-end > JS Tutorial > body text

Introduction to common methods of obtaining element instructions in js (with code)

不言
Release: 2018-08-21 14:42:05
Original
1960 people have browsed it

This article brings you an introduction to the common methods of obtaining element instructions in js (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

  • Obtain through the ID of the element: getElementById(); (for a single element)

(The following instructions often obtain an array, if To obtain one of the elements, the corresponding subscript should be added at the end)

  • Obtain through the class name of the element: getElementsByClassName();

  • Get through the tag name of the element: getElementsByTagName();

  • Get through the name of the element: getElementsByName();

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<span id="word">
			文字
		</span>
		<span class="words">
			文字
		</span>
		<span class="words">
			文字
		</span>
		<span class="words">
			文字
		</span>
		<input type="text" name="kuang" value="123" />
		<input type="text" name="kuang" value="456" />
		<input type="text" name="kuang" value="789" />
		
		<script type="text/javascript">
			var elements=document.getElementById("word");
			for (var i in elements) console.log(elements[i]);
			elements=document.getElementsByClassName("words");
			for (var i in elements) console.log(elements[i]);
			elements=document.getElementsByTagName("span");
			for (var i in elements) console.log(elements[i]);
			elements=document.getElementsByName("kuang");
			for (var i in elements) console.log(elements[i]);
			
                        element=document.getElementsByClassName("words")[0];
                        console.log(element);
		</script>
	</body>
</html>
Copy after login

In the browser The console can display the results:

Related recommendations:

js gets php (ecshop smarty template) array element value

js specific implementation of obtaining element collection through element class name_javascript skills

The above is the detailed content of Introduction to common methods of obtaining element instructions in js (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
js
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template