📜  getelementsbyclassname 添加类 (1)

📅  最后修改于: 2023-12-03 15:00:54.458000             🧑  作者: Mango

Introduction to getElementsByClassName()

getElementsByClassName() is a JavaScript method that allows you to select and return elements on a web page that have a specified classname. This method is useful when you want to retrieve all elements with the same classname and perform some task on them such as changing their styling or adding or removing them from the DOM.

Syntax

The syntax for using getElementsByClassName() is as follows:

document.getElementsByClassName(className);

The className parameter is a string that specifies the name of the class(es) you want to select. You can select multiple classes by separating them with spaces, as shown in the example below:

document.getElementsByClassName('example-class example-class-2');
Return Value

getElementsByClassName() returns a collection of HTML elements that have the specified classname. The collection is a live HTMLCollection, meaning that any changes made to the DOM will be reflected in the returned collection.

Example
<!DOCTYPE html>
<html>
<head>
	<title>getElementsByClassName Example</title>
	<style>
		.example-class {
			font-weight: bold;
			color: blue;
		}
	</style>
</head>
<body>
	<h1 class="example-class">Heading 1</h1>
	<p class="example-class">This is a paragraph.</p>
	<ul>
		<li class="example-class">List item 1</li>
		<li>List item 2</li>
		<li class="example-class">List item 3</li>
	</ul>
	<script>
		var exampleElements = document.getElementsByClassName('example-class');
		for (var i = 0; i < exampleElements.length; i++) {
			exampleElements[i].style.fontSize = '20px';
		}
	</script>
</body>
</html>

In the example above, we have a web page with various elements that have the example-class classname. We use getElementsByClassName() to select all of these elements and then loop through them, changing their font size to 20px using .style.fontSize. This results in all elements with the example-class classname appearing with a larger font size.