Four methods of obtaining JavaScript objects corresponding to elements are detailed in HTML

table of Contents

Elements and tags

specific method:

One, getElementById() method

Two, getElementsByClassName () method

         Three, getElementsByTagName () method

         Four, getElementsByName () method


Elements and tags:

Label: Refers to the general term of the label enclosed by a pair of <>.
Element: Refers to all the code from the start tag to the end tag. The element contains more content than the tag.

 

specific method:

One, getElementById() method

Function: Get all the elements whose id is the specified content.
Code example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<div id="ttt">
			<span>郑州大学</span><i>河南大学</i>
		</div>
		<!--document-->
		
		<script>
			var element = document.getElementById("ttt");//获取HTML元素对应javaS对象
			console.log(element);
		</script>
	</body>
</html>

Result display:

Two, getElementsByClassName () method

Role: Get all the elements whose class name is the specified content.
Code example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<p class="z">黄河水</p>
		<p class="z">长江水</p>

		<!--document-->
		
		<script>
			var elements = document.getElementsByClassName("z");
			console.log(document.getElementsByClassName("z")[0]);
			for(var i in elements){
				console.log(element[i]);
			}
			console.log("######################");
			for(var i=0;i<elements.length;i++){
				console.log(elements[i]);
			}
		</script>
	</body>
</html>

Result display:

Three, getElementsByTagName () method

Role: Get all elements whose tags are specified content.
Code example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<p class="z">黄河水</p>
		<p class="z">长江水</p>
	
		<!--document-->
		<script>
			
			console.log("######################");
			elements = document.getElementsByTagName("p");
			for(var i=0;i<elements.length;i++){
				console.log(elements[i]);
			}
		</script>
	</body>
</html>

Result display:

Four, getElementsByName () method

Role: Get all the elements whose name attribute is the specified content.
Code example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<input type="checkbox" name="hobby" />足球<input type="checkbox" name="hobby" />篮球<input type="checkbox" name="hobby" />乒乓球
	
		<script>
			
			console.log("######################");
			elements = document.getElementsByName("hobby");
			for(var i=0;i<elements.length;i++){
				console.log(elements[i]);
			}
			
			function tttt(){
				var element = document.getElementById("user_name");
				console.log(element.value);
			}
			
		</script>
	</body>
</html>

Result display:

 

Guess you like

Origin blog.csdn.net/m0_46383618/article/details/107431621
Recommended