Hướng Dẫn classlist remove 正規表現 2022

Mẹo Hướng dẫn classlist remove 正規表現 2022

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.

Add Remove, Toggle or Replace Class of an Element in JavaScript

Last Updated December 11, 2022

Author Monty Shokeen

Nội dung chính

    Add Remove, Toggle or Replace Class of an Element in JavaScriptAdd a Class to an HTML Element Using classNameRemove a Class From an HTML Element Using classNameReplace all Classes of an HTML Element with New Ones Using classNameAdding, Removing and Replacing Classes Using classListQuick SummaryVideo liên quan

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

Add a Class to an HTML Element Using className

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”;

Remove a Class From an HTML Element Using className

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.

Replace all Classes of an HTML Element with New Ones Using className

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";

Adding, Removing and Replacing Classes Using classList

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’);

Quick Summary

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

Clip classlist remove 正規表現 ?

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

Chia Sẻ Link Download classlist remove 正規表現 miễn phí

You đang tìm một số trong những ShareLink Download classlist remove 正規表現 Free.

Thảo Luận vướng mắc về classlist remove 正規表現

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 #正規表現

Phone Number

Recent Posts

Tra Cứu MST KHƯƠNG VĂN THUẤN Mã Số Thuế của Công TY DN

Tra Cứu Mã Số Thuế MST KHƯƠNG VĂN THUẤN Của Ai, Công Ty Doanh Nghiệp…

3 years ago

[Hỏi – Đáp] Cuộc gọi từ Số điện thoại 0983996665 hoặc 098 3996665 là của ai là của ai ?

Các bạn cho mình hỏi với tự nhiên trong ĐT mình gần đây có Sim…

3 years ago

Nhận định về cái đẹp trong cuộc sống Chi tiết Chi tiết

Thủ Thuật về Nhận định về nét trẻ trung trong môi trường tự nhiên vạn…

3 years ago

Hướng Dẫn dooshku là gì – Nghĩa của từ dooshku -Thủ Thuật Mới 2022

Thủ Thuật về dooshku là gì - Nghĩa của từ dooshku -Thủ Thuật Mới 2022…

3 years ago

Tìm 4 số hạng liên tiếp của một cấp số cộng có tổng bằng 20 và tích bằng 384 2022 Mới nhất

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…

3 years ago

Mẹo Em hãy cho biết nếu đèn huỳnh quang không có lớp bột huỳnh quang thì đèn có sáng không vì sao Mới nhất

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…

3 years ago