Cách xóa crossbrowse

Since element.classList is not supported in IE 9 và Safari-5, what"s an alternative sầu cross-browser solution?

No-frameworks please.

Bạn đang xem: Cách xóa crossbrowse

Solution must work in at least IE 9, Safari 5, FireFox 4, Opera 11.5, and Chrome.

Related posts (but does not contain solution):



One way to play around with classes without frameworks/libraries would be using the property Element.className, which "gets và sets the value of the class attribute of the specified element." (from the MDoanh Nghiệp documentation).As
matías-fidemraizer already mentioned in his answer, once you get the string of classes for your element you can use any methods associated with strings lớn modify it.

Here"s an example:Assuming you have a div with the ID "myDiv" & that you want to lớn add to lớn it the class "main__section" when the user clicks on it,

window.onload = init;function init() document.getElementById("myDiv").onclick = addMyClass;function addMyClass() var classString = this.className; // returns the string of all the classes for myDiv var newClass = classString.concat(" main__section"); // Adds the class "main__section" to the string (notice the leading space) this.className = newClass; // sets className to lớn the new string


Here is solution for addClass, removeClass, hasClass in pure javascript solution.

Actually it"s from http://jaketrent.com/post/addremove-classes-raw-javascript/

function hasClass(ele,cls) return !!ele.className.match(new RegExp("(\sfunction addClass(ele,cls) if (!hasClass(ele,cls)) ele.className += " "+cls;function removeClass(ele,cls) if (hasClass(ele,cls)) ^)"+cls+"(\s


I just wrote these up:

function addClass(el, classNameToAdd) el.className += " " + classNameToAdd; function removeClass(el, classNameToRemove) var elClass = " " + el.className + " "; while(elClass.indexOf(" " + classNameToRemove + " ") !== -1) elClass = elClass.replace(" " + classNameToRemove + " ", ""); el.className = elClass;I think they"ll work in all browsers.


Look at these oneliners:

Remove class:

element.classList.remove("hidden");Toggle class (adds the class if it"s not already present và removes it if it is)

element.classList.toggle("hidden");That"s all! I made a thử nghiệm - 10000 iterations. 0.8s.

Xem thêm: Cách Đăng Nhập Viber Trên Máy Tính Không Cần Quét Code

The simplest is element.classList which has remove(name), add(name), toggle(name), & contains(name) methods and is now supported by all major browsers.

For older browsers you change element.className. Here are two helper:

function addClass(element, className) element.className += " " + className; function removeClass(element, className) $)", "g"), " ").trim();
Read this Mozilla Developer Network article:

Since element.className property is of type string, you can use regular String object functions found in any JavaScript implementation:

If you want khổng lồ add a class, first use String.indexOf in order lớn check if class is present in className. If it"s not present, just concatenate a blank character and the new class name to lớn this property. If it"s present, bởi vì nothing.

If you want lớn remove a class, just use String.replace, replacing "" with an empty string. Finally use String.trlặng khổng lồ remove sầu blank characters at the start and over of element.className.


Do not use "class", as it is a reserved wordremoveClass functionwas broken, as it bugged out after repeated use.


function addClass(el, newClassName) el.className += " " + newClassName; function removeClass(el, removeClassName) var elClass = el.className; while(elClass.indexOf(removeClassName) != -1) elClass = elClass.replace(removeClassName, ""); elClass = elClass.trim(); el.className = elClass;
The solution is to

Shyên .classList:

Either use the DOM-shyên or use Eli Grey"s shim below

Disclaimer: I believe the tư vấn is FF3.6+, Opera10+, FF5, Chrome, IE8+

source http://purl.eligrey.com/github/classList.js/blob/master/classList.js*/if (typeof document !== "undefined" && !("classList" in document.createElement("a"))) {(function (view) {"use strict";var classListProp = "classList" , protoProp = "prototype" , elemCtrProto = (view.HTMLElement || view.Element) , objCtr = Object , strTrim = String.trlặng || function () s+$/g, ""); , arrIndexOf = Array.indexOf || function (item) { var i = 0 , len = this.length ; for (; i
Improved version of emil"s code (with trim())

function hasClass(ele,cls) return !!ele.className.match(new RegExp("(\sfunction addClass(ele,cls) if (!hasClass(ele,cls)) ele.className = ele.className.trim() + " " + cls;function removeClass(ele,cls) if (hasClass(ele,cls)) ^)"+cls+"(\s
function addClass(element, classString) element.className = element .className .split(" ") .filter(function (name) return name !== classString; ) .concat(classString) .join(" ");function removeClass(element, classString) element.className = element .className .split(" ") .filter(function (name) return name !== classString; ) .join(" ");
Just in case if anyone would lượt thích to lớn have prototype functions built for elements, this is what I use when I need to manipulate classes of different objects:

Element.prototype.addClass = function (classToAdd) var classes = this.className.split(" ") if (classes.indexOf(classToAdd) === -1) classes.push(classToAdd) this.className = classes.join(" ")Element.prototype.removeClass = function (classToRemove) var classes = this.className.split(" ") var idx =classes.indexOf(classToRemove) if (idx !== -1) classes.splice(idx,1) this.className = classes.join(" ")Use them like: document.toàn thân.addClass("whatever") or document.body.removeClass("whatever")

Instead of body you can also use any other element (div, span, you name it)

add css classes: cssClassesStr += cssClassName;

remove sầu css classes: cssClassStr = cssClassStr.replace(cssClassName,"");

add attribute "Classes": object.setAttribute("class", ""); //pure addition of this attribute

remove sầu attribute: object.removeAttribute("class");

A easy khổng lồ understand way:

Thanks for contributing an answer to lớn Stack Overflow!

Please be sure to lớn answer the question. Provide details và tóm tắt your research!

But avoid

Asking for help, clarification, or responding to lớn other answers.Making statements based on opinion; back them up with references or personal experience.

Xem thêm: Cách Copy Video Từ Iphone Sang Máy Tính Bằng Itunes, Cách Copy Ảnh Từ Iphone Sang Máy Tính Bằng Itunes

To learn more, see our tips on writing great answers.

Post Your Answer Disthẻ

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged javascript dom cross-browser or ask your own question.

site design / logo sản phẩm © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev2021.4.5.38984

Your privacy

By clicking “Accept all cookies”, you agree Staông xã Exchange can store cookies on your device and discthua thảm information in accordance with our Cookie Policy.

Chuyên mục: Theme wordpress