给DOM元素设置class是我们在项目中非常容易遇到的,网上的资料和总结也比较多,下面比较全面的整理一下,希望给到大家一些帮助!并引用两种成熟的classList的兼容方法

一、el.setAttribute('class','abc'); 

var div = document.getElementById('d1');
div.setAttribute("class", "abc");

兼容:IE8/9/10/Firefox/Safari/Chrome/Opera支持  IE6/7不支持setAttribute('class',xxx)方式设置元素的class。

二、el.setAttribute('className', 'abc') 

var div = document.getElementById('d1');
div.setAttribute("className",
"abc");

兼容:IE6/7支持  IE8/9/10/Firefox/Safari/Chrome/Opera不支持setAttribute('className',xxx)方式设置元素的class。

三、el.className = 'abc'; 

var div = document.getElementById('d1');
div.className = 'abc';

兼容:所有浏览器都支持。

四、classList属性

HTML5新增的JavaScript API,HTML5为每个元素定义了classLlist属性,用于在元素中添加,移除及切换 CSS 类。该属性是 DOMTokenList 对象(一个只读的类数组对象),你可以通过DOMTokenList定义的方法对其进行修改。

  1. add( class1, class2, ...)    在元素中添加一个或多个类名(如果指定的类名已存在,则不会添加)用法:`el.classList.add("a", "b", "c");`

  2. remove( class1, class2, ...)    删除元素中一个或多个类名用法:el.classList.remove('a','b');          

  3. toggle(class, true|false)    在元素中切换类名;参数1:要移出或者添加的类名;参数2:可选参数,不论类名是否存在,为true时强制添加类名,false时强制删除类名;用法: 添加:el.classList.toggle("d", true);删除:el.classList.toggle("d", false);           

  4. contains( class )    判断指定的类名是否存在;用法:el.classList.contains("e") ,//如果e存在返回true 

  5. item(index)    根据索引返回类名,索引从 0 开始,如果没有则返回null;用法:el.classList.item(0) //返回e

  6. length属性 var len = document.body.classList.length;

兼容:支持classList属性的浏览器有Firefox 3.6+,ie10+和Chrome。IE9和IE9以前的版本不支持该属性,移动端方面,除了安卓2.3及以下版本的webview不支持,其它浏览器终端都能很好地支持。

最后,给不支持classList的浏览器(ie9及以下等)总结两种兼容解决方案:

第一种:

  1. if (!("classList" in document.documentElement)) {
  2. Object.defineProperty(HTMLElement.prototype, 'classList', {
  3. get: function() {
  4. var self = this;
  5. function update(fn) {
  6. return function(value) {
  7. var classes = self.className.split(/\s+/g),
  8. index = classes.indexOf(value);
  9. fn(classes, index, value);
  10. self.className = classes.join(" ");
  11. }
  12. }
  13. return {
  14. add: update(function(classes, index, value) {
  15. if (!~index) classes.push(value);
  16. }),
  17. remove: update(function(classes, index) {
  18. if (~index) classes.splice(index, 1);
  19. }),
  20. toggle: update(function(classes, index, value) {
  21. if (~index)
  22. classes.splice(index, 1);
  23. else
  24. classes.push(value);
  25. }),
  26. contains: function(value) {
  27. return !!~self.className.split(/\s+/g).indexOf(value);
  28. },
  29. item: function(i) {
  30. return self.className.split(/\s+/g)[i] || null;
  31. }
  32. };
  33. }
  34. });
  35. }

第二种:从新写了方法,比前一种代码多点,原文出处

    var classList = null;
(function(){
classList = function (obj){
this.obj = obj;
};
classList.prototype.add = function(value){
if(typeof value !== "string") throw TypeError("the type of value is error");
if(this.obj.classList){
this.obj.classList.add(value);
}else{
var arr = value.replace(/^\s+|\s+$/g,"").split(/\s+/);
this.obj.classList +=" "+arr.join(" ");
}
};
classList.prototype.contains = function(value){
if(typeof value !== "string") throw TypeError("the type of value is error");
if(this.obj.classList){
return this.obj.classList.contains(value);
}else{
var arr = value.replace(/^\s+|\s+$/g,"").split(/\s+/);
var _className = this.obj.className;
for(var i = 0,len= arr.length; i<len; i++){
if(_className.search(new RegExp("(\\s+)?"+arr[i]+"(\\s+)?"))===-1){
return false;
}
}
return true;
}
};
classList.prototype.remove = function(value){
if(typeof value !== "string") throw TypeError("the type of value is error");
if(this.obj.classList){
return this.obj.classList.remove(value);
}else{
var arr = value.replace(/^\s+|\s+$/g,"").split(/\s+/);
var _className = this.obj.className;
for(var i = 0, len = arr.length;i<len; i++){
if(_className.search(new RegExp("(\\s+)?"+arr[i]+"(\\s+)?"))!==-1){
_className = _className.replace(new RegExp("(\\s+)?"+arr[i]+"(\\s+)?"),"");
}
}
this.obj.className = _className;
}
};
classList.prototype.toggle = function(value){
if(typeof value !== "string") throw TypeError("the type of value is error");
if(this.contains(value)){
this.remove(value);
}else{
this.add(value);
}
};
})(); ps:附上张鑫旭博客中关于classList的文章,让你理解的更透彻!
HTML5 DOM元素类名相关操作API classList简介
												

js设置元素class方法小结及classList相关的更多相关文章

  1. js面向对象 多种创建对象方法小结

    转自js面向对象 多种创建对象方法小结 1.对象字面量 var clock={ hour:12, minute:10, second:10, showTime:function(){ alert(th ...

  2. js设置元素不能编辑

    js设置元素不能编辑 $("#startLocation").attr("readOnly",true); js设置元素可以编辑 $("#startL ...

  3. js设置元素float的问题

    用js设置一个元素的float样式 div.style.float = 'left'; 这句话在谷歌浏览器或许没问题,但是在IE,火狐下会无效 正确写法是 div.style.styleFloat = ...

  4. ***php 数组添加关联元素的方法小结(关联数组添加元素)

    我们这里介绍的是在数组中再增加关联数组了,这个就合成了多维数组,下面我来给大家举几个实例,希望对各位同学会有所帮助哈. 在"php 数组添加元素方法总结这篇文章中介绍了如何给数组添加元素,那 ...

  5. js设置元素的onclick传参方法

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD ...

  6. js生成随机数的方法小结

    js生成随机数主要用到了内置的Math对象的random()方法.用法如:Math.random().它返回的是一个 0 ~ 1 之间的随机数.有了这么一个方法,那生成任意随机数就好理解了.比如实际中 ...

  7. 使用js获取QueryString的方法小结

    一.<script> urlinfo=window.location.href; //获取当前页面的url len=urlinfo.length;//获取url的长度 offset=url ...

  8. MySQL数据库设置远程访问权限方法小结

    http://www.jb51.net/article/42441.htm MySQL基础知识第一期,如何远程访问MySQL数据库设置权限方法总结,讨论访问单个数据库,全部数据库,指定用户访问,设置访 ...

  9. js设置元素指定时间隐藏

    $().fadeOut(); js指定时间隐藏

随机推荐

  1. ABP module-zero +AdminLTE+Bootstrap Table+jQuery权限管理系统第十六节--SignalR与ABP框架Abp.Web.SignalR及扩展

    SignalR简介 SignalR是什么? ASP.NET SignalR 是为 ASP.NET 开发人员提供的一个库,可以简化开发人员将实时 Web 功能添加到应用程序的过程.实时 Web 功能是指 ...

  2. node.js之fs模块

    一.fs模块的mkdir函数,创建文件夹 var http = require("http"); var fs = require("fs"); var ser ...

  3. 【HNOI2002】营业额统计

    https://www.luogu.org/problem/show?pid=2234 用Treap维护,每次查询这个数的前驱与后继哪个和它差值更小. 由于查询一个数时在Treap走出的路径必定经过它 ...

  4. PHP curl_setopt函数用法介绍

    [导读] curl_setopt函数是php中一个重要的函数,它可以模仿用户的一些行为,如模仿用户登录,注册等等一些用户可操作的行为哦.bool curl_setopt (int ch, string ...

  5. UVA 12009 - Avaricious Maryanna(数论)

    UVA 12009 - Avaricious Maryanna 题目链接 题意:给定一个n.求出n个数位组成的数字x,x^2的前面|x|位为x 思路:自己先暴力打了前几组数据,发现除了1中有0和1以外 ...

  6. ftk学习记(list篇)

    [声明:版权全部,欢迎转载.请勿用于商业用途. 联系信箱:feixiaoxing @163.com] 在開始今天的list主题之前,先看一下icon的执行效果. 今天说的list事实上和这个icon几 ...

  7. EularProject 43: 带条件约束的排列组合挑选问题

    Sub-string divisibility Problem 43 The number, 1406357289, is a 0 to 9 pandigital number because it ...

  8. java多线程编程核心技术——第六章总结

    目录 1.0立即加载/"饿汉式" 2.0延迟加载/"懒汉式" 3.0使用静态内置类实现单例模式 4.0序列化与反序列化的单例模式实现 5.0使用static代码 ...

  9. 八、 Spring Boot 过滤器、监听器

    直接使用@WebFilter和@WebListener的方式,完成一个Filter 和一个 Listener.过滤器(Filter)文件MyFilter.Javapackage org.springb ...

  10. java.net.BindException: Cannot assign requested address: bind

    异常信息 时间:2017-03-16 10:21:05,644 - 级别:[ERROR] - 消息: [other] Failed to start end point associated with ...