html 按类名获取元素

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html 按类名获取元素相关的知识,希望对你有一定的参考价值。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>DOM TEST</title>
</head>
<body>
	<div id="container">
		<div class="row">
			<h1>Hello World</h1>
			<a href="#">Click Here</a>
		</div>
		<div class="row">
			<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum beatae quas praesentium. Distinctio hic vel nihil, eum facilis doloremque incidunt atque autem dolor est esse fugit tempora ea magni, quis.</p>
		</div>
		<div class="row">
			<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit, sunt provident et dicta, dolores, deleniti, sint unde assumenda nulla doloremque neque. Velit at praesentium cum delectus quae optio. Quisquam, veritatis.</p>
		</div>
		<div class="row">
			<ul>
				<li><a href="#">How are you</a></li>
				<li><a href="#">How do you do</a></li>
				<li><a href="#">What are you doing</a></li>
				<li><a href="#">Where do you live</a></li>
			</ul>
		</div>
	</div>

	<script>
		var container = document.getElementById("container");
		container.style.backgroundColor = "#e3e3e3";
		container.style.padding = "20px";

		var myHeader = document.getElementsByTagName("h1");
		console.log(myHeader);
		myHeader[0].style.color = "red";
		var myLinks = document.getElementsByTagName("a");
		console.log(myLinks);
		myLinks[1].style.color = "green";

		var myRows = document.getElementsByClassName("row");
		myRows[0].style.backgroundColor = "red";
		myRows[1].style.backgroundColor = "green";

		var myThirdRow = myRows[2];
		var myThirdRowP = myThirdRow.getElementsByTagName("p");
		myThirdRowP[0].style.color = "#673AB7";

	</script>

</body>
</html>

以上是关于html 按类名获取元素的主要内容,如果未能解决你的问题,请参考以下文章

如果类名是数字,则无法按类名获取元素

JQuery:如何从没有根元素的 HTML 数据中按类名获取 div

JavaScript 按类名获取元素

使用 Elm.Browser.Dom 按类名获取元素

按类名收集元素,然后单击每个元素 - Puppeteer

Selenium 在python中按类名查找元素