JS set element class method summary and Classlist correlation

Source: Internet
Author: User

Set the DOM element class is we are very easy to encounter in the project, the online information and summary is more, the following more comprehensive collation, I hope to give you some help! and reference to two mature classlist compatibility methods

One, El.setattribute (' class ', ' abc ');

var div = document.getElementById (' D1 ');
Div.setattribute ("Class", "abc");

Compatible: Ie8/9/10/firefox/safari/chrome/opera support IE6/7 does not support setattribute (' class ', XXX) way to set the class of the element.

Ii. el.setattribute (' className ', ' abc ')

var div = document.getElementById (' D1 ');
Div.setattribute ("ClassName", "abc");

Compatible: IE6/7 support Ie8/9/10/firefox/safari/chrome/opera does not support setattribute (' className ', XXX) way to set the class of the element.

Third, el.classname = ' abc ';

var div = document.getElementById (' D1 ');
Div.classname = ' abc ';

Compatible: All browsers are supported.

Iv.. Classlist Properties

HTML5 new JavaScript API,HTML5 defines the classllist attribute for each element, which is used to add, remove, and toggle CSS classes in the element. This property is a Domtokenlist object (a read-only class array object) that you can modify by means of the domtokenlist definition.

  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;

Compatible: Browsers that support Classlist properties have Firefox 3.6+,ie10+ and Chrome. IE9 and IE9 Previous versions do not support this property, the mobile side, in addition to Android 2.3 and the following version of the WebView is not supported, other browser terminal can be very well supported.

Finally, two compatible solutions are summarized for browsers that do not support classlist (IE9 and below):

The first type:

  1. if (! ( "Classlist" in document.documentelement)) {  
  2. Object.defineproperty (Htmlelement.prototype, ' classlist ', {
  3. Get: function () {
  4. var = 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. }

The second type: from the new method, more than the previous code, the source of the original

    var classlist =null;    (function() {classlist =function(obj) {This.obj = obj; }; ClassList.prototype.add =function(value) {Iftypeof Value!=="String")ThrowTypeError ("The type of value is Error");IfThis.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) {Iftypeof Value!=="String")ThrowTypeError ("The type of value is Error");IfThis.obj.classList) {ReturnThis.obj.classList.contains (value); }else{var arr = Value.replace (/^\s+|\s+$/g,""). Split (/\s+/);var _classname =This.obj.className;Forvar i =0,len= arr.length; i<len; i++) {if (_classname.search (NewREGEXP ("(\\s+)?" +arr[i]+"(\\s+)?") ===-1) {ReturnFalse } }ReturnTrue } }; ClassList.prototype.remove =function(value) {Iftypeof Value!=="String")ThrowTypeError ("The type of value is Error");IfThis.obj.classList) {ReturnThis.obj.classList.remove (value); }else{var arr = Value.replace (/^\s+|\s+$/g,""). Split (/\s+/);var _classname =This.obj.className;Forvar i =0, Len = arr.length;i<len; i++) {if (_classname.search (NewREGEXP ("(\\s+)?" +arr[i]+"(\\s+)?")! ==-1) {_classname = _classname.replace (Newregexp ( "(\\s+)?" +arr[i]+this.obj.classname = _classname;} }; ClassList.prototype.toggle = function if (typeof value!==  "string") throw typeerror ( "the type of value is Error"); if (this.contains (value)) { This.remove (value); }else{this.add (value);}};}) (); 

PS: Attach Zhang Xin Xu blog about classlist articles, let you understand more thoroughly!
HTML5 DOM element class name related Operations API Classlist introduction

JS set element class method summary and Classlist correlation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.