When developing web pages, many times we need to operate elements with the same class name, that is, elements with the same class. I took the written test yesterday and I couldn’t answer a related question:
JavaScript gets the node with class test in the page
So I collected some relevant information and listed two methods that I think are better in this article. If there are any shortcomings, I hope everyone can criticize and correct them. If you have a better method, I hope you can share it.
Solution1 Jeremy Keuth Solution
Uncle Jeremy Keuth talked about the getElementsByClass method in Chapter 3, Section 4 of the book "The Art of JavaScript DOM Programming (2nd Edition)" (English: DOM Scripting-Web Design with JavaScript and the Document Object Model). It also talks about how to apply this method in browsers that do not support this attribute (IE6, IE7 and IE8, let us despise them). The excerpt is here, with modifications in some places.
There is a new method in HTML5 DOM that allows us to access elements through the class name in the class attribute. This is: getELementsByClassName. Since the method is relatively new, it is not yet available in some DOM implementations, so be careful when using it. . Let's first take a look at what this method can do for us, and then discuss how to use this method reliably.
Similar to the getELementsByTagName method, getElementsByClassName only accepts one parameter, which is the class name:
getElementsByClassName(class)
The return value of this method is also similar to getElementsByTagName. It is an array of elements with the same class name. The following line of code returns an array containing all elements with the class name "sale":
document.getElementsByClassName("sale")
You can also use this method to find elements with multiple class names. To specify multiple class names, simply separate the class names with spaces in the string argument. For example, add the following line of code to the <script> tag: <br>
<div class="codetitle">
<span><a style="CURSOR: pointer" data="71155" class="copybut" id="copybut71155" onclick="doCopy('code71155')"><u>Copy code</u></a></span> The code is as follows:</div>
<div class="codebody" id="code71155">
<br>
alert(document.getElementsByClassName("sale important").length);<br>
</div>
<p><strong>Full code</strong></p>
<p></p>
<div class="codetitle">
<span><a style="CURSOR: pointer" data="10676" class="copybut" id="copybut10676" onclick="doCopy('code10676')"><u>Copy code</u></a></span> The code is as follows:</div>
<div class="codebody" id="code10676">
<br>
<!DOCTYPE html><br>
<html> <br>
<head><br>
<meta charset="utf-8"> <br>
<title>Shopping List</title><br>
</head> <br>
<body><br>
<h1>What to buy</h1><br>
<p title="a gentle reminder">Don't forget to buy this stuff.</p><br>
<ul id="purchase"><br>
</ul><br>
<script><br>
alert(document.getElementsByClassName("sale important").length);<br>
</script>