SoFunction
Updated on 2025-03-01

Native js implementation addClass, removeClass, hasClass methods

This article is divided into two parts for explanation, the specific content is as follows

Part One:Native js implementation addClass, removeClass, hasClass methods

function hasClass(elem, cls) {
  cls = cls || '';
  if ((/\s/g, '').length == 0) return false; //Return false when cls has no parameters  return new RegExp(' ' + cls + ' ').test(' ' +  + ' ');
}

function addClass(ele, cls) {
  if (!hasClass(elem, cls)) {
     =  == '' ? cls :  + ' ' + cls;
  }
}

function removeClass(ele, cls) {
  if (hasClass(elem, cls)) {
    var newClass = ' ' + (/[\t\r\n]/g, '') + ' ';
    while ((' ' + cls + ' ') >= 0) {
      newClass = (' ' + cls + ' ', ' ');
    }
     = (/^\s+|\s+$/g, '');
  }
}

Part 2:Use native JS to implement jQuery's addClass, removeClass, hasClass function function

function addClass(obj, cls){
  var obj_class = ,//Get class content.  blank = (obj_class != '') ? ' ' : '';//Discern whether the obtained class is empty, if it is not empty, add a 'space' before it.  added = obj_class + blank + cls;//Combined the original class and the class that needs to be added.   = added;//Replace the original class.}
 
function removeClass(obj, cls){
  var obj_class = ' '++' ';//Get the class content and add a space at the beginning and end. ex) 'abc bcd' -> ' abc bcd '  obj_class = obj_class.replace(/(\s+)/gi, ' '),//Replace the extra null characters with a space. ex) ' abc bcd ' -> ' abc bcd '  removed = obj_class.replace(' '+cls+' ', ' ');//Replace the class with spaces added to the beginning and end in the original class. ex) ' abc bcd ' -> 'bcd '  removed = (/(^\s+)|(\s+$)/g, '');//Remove the beginning and end spaces. ex) 'bcd ' -> 'bcd'   = removed;//Replace the original class.}
 
function hasClass(obj, cls){
  var obj_class = ,//Get class content.  obj_class_lst = obj_class.split(/\s+/);//Convert cls into an array through split empty character.  x = 0;
  for(x in obj_class_lst) {
    if(obj_class_lst[x] == cls) {//Loop the array to determine whether it contains cls      return true;
    }
  }
  return false;
}

The above is all about this article, I hope it will be helpful for everyone to learn JavaScript programming.