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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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