Contents
Bạn đang tìm kiếm từ khóa classlist remove 正規表現 được Update vào lúc : 2022-01-06 06:12:18 . Với phương châm chia sẻ Mẹo về trong nội dung bài viết một cách Chi Tiết 2022. Nếu sau khi đọc Post vẫn ko hiểu thì hoàn toàn có thể lại Comments ở cuối bài để Admin lý giải và hướng dẫn lại nha.
Last Updated December 11, 2022
Author Monty Shokeen
Nội dung chính
Almost all website projects that we work on require us to change the classes of different HTML elements one time or other. We can do this very easily using jQuery. However, using a library just to change or manipulate the classes of different DOM element is overkill. In this post, we will cover different methods to achieve all this using pure JavaScript.
On This Page
The className property can be used to get or set the value of the class attribute of any DOM element. The returned string contains all the classes of current element separated by a space. We can simply use the += operator to append any new classes to our element.
JavaScript
document.getElementById(“theId”).className += ” extraClass”;
document.querySelector(“selector”).className += ” extraClass”;
If you want to add a class to multiple HTML elements once, you can use the document.querySelectorAll() method to do so.
JavaScript
var elems = document.querySelectorAll(“selector”);
var elemCount = elems.length;
for (var i = 0; i < elemCount; i++)
elems[i].className += " extraClass";
You can also use the document.querySelectorAll() method to assign extra classes a selected HTML element a specific index.
JavaScript
document.querySelectorAll(“selector”)[index] += ” extraClass”;
One disadvantage of adding classes this way is that if you are not careful, a class might be added several times. We can implement a check to see if class already exists for an HTML element and not add it if it does.
JavaScript
var elem = document.getElementById(“theId”);
if(elem.className.match( /(^|s+)extraClass($|s+)/g))
elem.className += ” extraClass”;
You can also use the className property to remove a specific class from the class attribute of an HTML element. This requires the use of regex to replace the unwanted class with an empty string.
JavaScript
var elem = document.getElementById(“theId”);
elem.className = elem.className.replace( /(^|s+)extraClass($|s+)/g , ” );
In the above regular expression, the first capture group either captures the beginning of a string or any whitespace characters. Similarly, the second capture group either captures the end of a string or any whitespace characters. The string between these two capture groups is the class name that you want to replace. Here are some of the results of using the above regular expression to replace unwanted classes:
JavaScript
Regular Expression (^|s+)dark($|s+)/g
Classes “heading page-title dark large”
After Removal “heading page-title large”
Regular Expression (^|s+)title($|s+)/g
Classes “heading page-title dark large”
After Removal “heading page-title dark large”
Regular Expression (^|s+)large($|s+)/g
Classes “heading page-title dark large”
After Removal “heading page-title dark”
In the second case, there was no title class in the whole list so nothing was replaced. The page-title class remained intact.
Just like the previous section, you can loop through multiple elements and remove a class from all of them using the docment.querySelectorAll() method.
You can also replace all classes of an HTML element with new ones by assigning the new class string to that element instead of appending it to the original set of classes.
JavaScript
document.getElementById(“theId”).className = “firstClass secondClass”;
document.querySelector(“selector”).className = “firstClass”;
Similarly, you can assign new classes to multiple elements by looping over them.
JavaScript
var elems = document.querySelectorAll(“selector”);
var elemCount = elems.length;
for (var i = 0; i < elemCount; i++)
elems[i].className = "extraClass";
If you are working with modern browsers, you can avoid the use of regular expressions while changing the classes of an HTML element. All modern browsers as well as Internet Explorer 10 and above tư vấn a classList property for DOM elements. This property has some useful methods which can add and remove classes from the class attribute of any HTML element.
The add(String [, String]) method accepts name of one or more classes as its parameters. These classes are added to the original HTML element on which this method was called. If any of those classes already exist in that element, there will be ignored. This way you can be sure that the same class is not added multiple times.
The remove(String [, String]) method also accepts name of one or more classes as its parameters. All the classes supplied to this method will be deleted from the list of classes initially applied on the calling HTML element. One good thing about the method is that it will not through an error if the class that youre going to delete does not already exist in that element.
You can also use the toggle(String [, force]) method to toggle a class currently applied on the calling HTML element. If the class already exists, it will be removed and the method will return false. If a class does not exist, it will be added to the list of classes and the method will return true. The force parameter is a Boolean value which can be used to forcefully add or remove a class from the calling HTML element. A class will be added if the value of force evaluates to true. Similarly, the class will be removed if the value of force evaluates to false.
Instead of adding or removing classes, you might sometimes be interested in replacing an old class with a new one. This can be achieved using the replace(oldClass, newClass) method. The first parameter passed to this method is the old class that you want to replace. The second parameter is the new class meant to take the place of old class.
The class list property also has a contains(String) method which can check if an HTML element contains a class or not.
JavaScript
var theClassList = document.querySelector(“selector”).classList;
theClassList.add(‘firstClass’);
theClassList.remove(‘secondClass’);
theClassList.toggle(‘thirdClass’);
theClassList.replace(‘thirdClass’, ‘fourthClass’);
Lets recap everything that we have covered in this tutorial.
If you have to tư vấn older browsers the best way to add, remove or replace any class in an HTML element is to use the className property. However, you will have to be careful about a few things like not adding a class multiple times etc.If you dont have to tư vấn older browsers the best way to change the classes of an HTML element is to use the classList property. This will take care of everything for you.
Let me know if there is anything that you would like me to clarify in this tutorial. Also, you are more than welcome to comment if you know other techniques to add, remove or replace the classes of an HTML element using JavaScript.
Share With Friends
Rate this post
(8 votes, average: 3.88 out of 5)
Loading…SubscribeNotify ofLabel [+] Name* E-Mail* Website Label [+] Name* E-Mail* Website 2 CommentsOldestNewest Most VotedInline FeedbacksView all commentsaria5 months ago
sorry the code doesnt work
0 ReplyAdminTutorialo Team(@ukqonyvw)4 months agoReply to aria
Hi aria,
Could you please tell me which part of the code isnt working?
0 Reply
Bạn vừa Read tài liệu Với Một số hướng dẫn một cách rõ ràng hơn về Video classlist remove 正規表現 tiên tiến và phát triển nhất
You đang tìm một số trong những ShareLink Download classlist remove 正規表現 Free.
Nếu sau khi đọc nội dung bài viết classlist remove 正規表現 vẫn chưa hiểu thì hoàn toàn có thể lại Comment ở cuối bài để Admin lý giải và hướng dẫn lại nha
#classlist #remove #正規表現
Tra Cứu Mã Số Thuế MST KHƯƠNG VĂN THUẤN Của Ai, Công Ty Doanh Nghiệp…
Các bạn cho mình hỏi với tự nhiên trong ĐT mình gần đây có Sim…
Thủ Thuật về Nhận định về nét trẻ trung trong môi trường tự nhiên vạn…
Thủ Thuật về dooshku là gì - Nghĩa của từ dooshku -Thủ Thuật Mới 2022…
Kinh Nghiệm Hướng dẫn Tìm 4 số hạng liên tục của một cấp số cộng…
Mẹo Hướng dẫn Em hãy cho biết thêm thêm nếu đèn huỳnh quang không còn…