Now, I want to create a JavaScript function that will add a class to the div (not replace, but add).

Đang xem: How to add a class to an element with vanilla javascript

How can I do that?

*

*

If you”re only targeting modern browsers:Use element.classList.add to add a class:

element.classList.add(“my-class”);And element.classList.remove to remove a class:

element.classList.remove(“my-class”);If you need to support Internet Explorer 9 or lower:Add a space plus the name of your new class to the className property of the element. First, put an id on the element so you can easily get a reference.

*

*

The easiest way to do this without any framework is to use element.classList.add method.

var element = document.getElementById(“div1”);element.classList.add(“otherclass”);Edit:And if you want to remove class from an element –

element.classList.remove(“otherclass”);I prefer not having to add any empty space and duplicate entry handling myself (which is required when using the document.className approach). There are some browser limitations, but you can work around them using polyfills.

Xem thêm: Xem Dấu Hiệu Chàng Yêu Bạn Chỉ Vì Chuyện Ấy, 9 Dấu Hiệu Chàng Yêu Bạn Dù Chưa Tỏ Tình

find your target element “d” however you wish and then:

d.className += ” additionalClass”; //note the spaceyou can wrap that in cleverer ways to check pre-existence, and check for space requirements etc..

Add Class

Cross Compatible

In the following example we add a classname to the element. This is IE-8 compatible.

var a = document.body;a.classList ? a.classList.add(“classname”) : a.className += ” classname”;This is shorthand for the following..

Xem thêm: ” Last But Not Least Nghĩa Là Gì, 5 Cụm Từ Cần Tránh Trong Ielts Writing

var a = document.body;if (a.classList) { a.classList.add(“wait”);} else { a.className += ” wait”;}Performance

If your more concerned with performance over cross-compatibility you can shorten it to the following which is 4% faster.

var z = document.body;document.body.classList.add(“wait”);Convenience

Alternatively you could use jQuery but the resulting performance is significantly slower. 94% slower according to jsPerf

$(“body”).addClass(“wait”);

Removing the class

Performance

Using jQuery selectively is the best method for removing a class if your concerned with performance

var a = document.body, c = ” classname”;$(a).removeClass(c);Without jQuery it”s 32% slower

var a = document.body, c = ” classname”;a.className = a.className.replace( c, “” );a.className = a.className + c;

References

Using Prototype

Element(“document.body”).ClassNames.add(“classname”)Element(“document.body”).ClassNames.remove(“classname”)Element(“document.body”).ClassNames.set(“classname”)

Using YUI

YAHOO.util.Dom.hasClass(document.body,”classname”)YAHOO.util.Dom.addClass(document.body,”classname”)YAHOO.util.Dom.removeClass(document.body,”classname”)

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *