A detailed explanation of Javascript class selector methods
This article will introduce you to the Javascript class selector method. I hope it will be helpful to friends in need!
Javascript class selector method
As an ecosystem and platform, the browser will provide a series of function methods that can be called and controlled by programming languages. For browsing For the browser, it is natural to call the browser's built-in method through Javascript language. For the operating system, most languages can call its API.
CSS can add styles to HTML elements through id selectors or class selectors. The browser platform, like CSS, also provides id selectors and class selector methods that can be called by the Javascript language. Used before The id selector method is getElementById()
, and the class selector method to be explained in this article is getElementsByClassName()
. You can see what they want to express by their names. Standards Committee The formulation of these standards is not just a random naming on a whim. We try our best to keep the name as the name implies. Of course, this is for the English language as the name implies.
The characteristic of ID is to select one, and select the characteristics of class in batches. For example, to dynamically add style attributes to some elements in batches through Javascript, the getElementsByClassName()
method is mainly used. [Related recommendations: JavaScript Video Tutorial]
Case
Add Javascript code based on an already written HTML and css file. Enables users to batch customize the styles of elements on web pages.
48 <body style="background-color: #777777"> 49 <!--自定义颜色功能按钮--> 50 <button style="background-color: #00aaff" id="button1" onclick="fun1()"></button> 51 <button style="background-color: #1abc9c" id="button2" onclick="fun2()"></button> 52 <!--Web应用界面命令--> 53 <div class="command"> 54 <!--注释空格--> 55 <div class="bottom padding radius left-radius div">圆弧</div><!-- 56 --><div class="bottom padding div">直线</div><!-- 57 --><div class="bottom padding div">矩形</div><!-- 58 --><div class="bottom padding div">曲线</div><!-- 59 --><div class="padding right-radius div">倒角</div> 60 </div> 61 <script> 62 // 批量选中类属性名为div的所有元素,返回所有元素对象组成的数组 63 let arr = document.getElementsByClassName("div"); 64 // 定义两个更改颜色的函数fun1和fun2 65 function fun1() { 66 // 遍历所有元素对象 67 for(let i = 0; i<arr.length;i++){ 68 // 更改背景颜色 69 arr[i].style.backgroundColor="#00aaff"; 70 } 71 } 72 function fun2() { 73 for(let i = 0; i<arr.length;i++){ 74 arr[i].style.backgroundColor="#1abc9c"; 75 } 76 } 77 </script> 78 </body>
Code analysis
Lines 53 to 60 of the code define a series of command buttons for the application interface. Lines 50 and 51 of the code define two custom buttons. Element-style function button button. When you click one of the function button buttons, the function fun1() or fun2() in the script tag will be called. For example, after executing the fun1 function, the elements defined in lines 53 to 60 of the code The color of the background elements will be modified in batches from gray to #00aaff
color.
The 63rd line of code selects all elements whose class attribute name is "div" through the class selector method getElementsByClassName()
The object returned by the getElementById() method is the element itself, getElementsByClassName()
The method returns an array composed of all element objects. This means that if you want to change the attribute value of an element, access the element through array subscripts. For example, arr[0] represents the div element defined in line 55 of the code. If you directly write arr.style.backgroundColor="#00aaff";
it is illegal to change the background color of all elements in arr. arr is an array and it does not have a .style style attribute. You need to pass arr [i].style.backgroundColor="#00aaff
This form resets the background color of the element.
There are many elements to be changed, and the colors of the elements to be changed are also the same, so you can use for To complete the loop structure program, the function of lines 67 to 70 of the code is to traverse all div elements in the array arr, and then change their background color.
Lines 65 and 72 define functions respectively fun1 and fun2 can be called through mouse click events. The function of fun1 is to change the background color of elements to #00aaff in batches. The function of fun1 is to change the background color of elements to #1abc9c in batches.
<strong>getElementsByTagName()</strong>
getElementsByTagName()
method can be used to select elements in batches like the getElementsByClassName()
method. The returned The results are all array objects from the perspective of data type. The difference is that the getElementsByTagName() method selects elements through their tag names. The knowledge point corresponding to CSS is the element selector. The English Tag in the getElementsByTagName() method name is The meaning of the label.
Application
I have learned some methods of selecting elements and know their respective characteristics, just for application, how to choose getElementById() in actual application , getElementsByClassName() and getElementsByTagName(). You can refer to CSS for this. In CSS, class selectors are generally used. Element and id selectors are occasionally used, and the tag name of the element is used to select elements. If there are many places in a complete page They all require a certain element, and these elements require different background colors, for example. If you use the getElementsByTagName() method, it will be accidentally damaged. The advantage of getElementsByClassName() is that you can directly paste a class attribute name on the one you want to select. One element can There are multiple class names. In actual projects, code reuse is often emphasized. Code reuse is actually classification. For example, a website often has a theme background color, and tens of thousands of pages on the website are all a certain color. You only need Define a color class style and then introduce this class name on each page.
Summarize
This article not only explains the getElementsByClassName() method, but also explains the three methods of selecting elements in Javascript through comparison, which correspond to the element selector, id selector, and class selector in CSS. By comparing CSS selection and Javascript selector (DOM method) to reduce the memory burden of learning, learn technology from a system perspective, and understand a technical standard from the perspective of a standard committee developer.
The above is the detailed content of A detailed explanation of Javascript class selector methods. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
