Home > Web Front-end > JS Tutorial > Native javascript implements addClass, removeClass, hasClass functions_javascript skills

Native javascript implements addClass, removeClass, hasClass functions_javascript skills

WBOY
Release: 2016-05-16 15:13:50
Original
1190 people have browsed it

原生的addClass, removeClass, hasClass函数,未使用jquery

class.js

function hasClass(ele,cls) {
  return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
 
function addClass(ele,cls) {
  if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
 
function removeClass(ele,cls) {
  if (hasClass(ele,cls)) {
    var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
    ele.className=ele.className.replace(reg,' ');
  }
}
 
//call the functions
addClass(document.getElementById("test"), "test");
removeClass(document.getElementById("test"), "test")
if(hasClass(document.getElementById("test"), "test")){//do something};
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template