classList简介

2018-12-24  本文已影响0人  __越过山丘__

1. API概要

document.body.classList.item(0);

如果索引超出范围,例如:

document.body.classList.item(3);

结果是:null.

例如:

document.body.classList.add("c");

document.body.classList.length    // 3
document.body.classList.remove("c");
document.body.classList.length    // 2

返回值很易懂的。如果包含,则返回true, 不包含,则false. 例如:

document.body.classList.contains("c");    // false 因为"c"上面remove掉了

扩展一个adds方法,可以一次添加多个类名,多个类名以空格分隔:

DOMTokenList.prototype.adds = function(tokens) {
   tokens.split(" ").forEach(function(token) {
       this.add(token);
   }.bind(this));
   return this;
};

var clList = document.body.classList;
clList.adds("child1 child2 child3").toString(); // "a b c child1 child2 child3"

原文:https://www.zhangxinxu.com/wordpress/2013/07/domtokenlist-html5-dom-classlist-%E7%B1%BB%E5%90%8D/

上一篇 下一篇

猜你喜欢

热点阅读