add class with JavaScript

前端 未结 7 2014
傲寒
傲寒 2020-12-29 02:38

I am writing some vanilla JavaScript to create a nice navigation menu. I am stuck on adding an active class.

I am getting elements by class name NOT by id. The belo

相关标签:
7条回答
  • 2020-12-29 03:01

    Simply add a class name to the beginning of the funciton and the 2nd and 3rd arguments are optional and the magic is done for you!

    function getElementsByClass(searchClass, node, tag) {
    
      var classElements = new Array();
    
      if (node == null)
    
        node = document;
    
      if (tag == null)
    
        tag = '*';
    
      var els = node.getElementsByTagName(tag);
    
      var elsLen = els.length;
    
      var pattern = new RegExp('(^|\\\\s)' + searchClass + '(\\\\s|$)');
    
      for (i = 0, j = 0; i < elsLen; i++) {
    
        if (pattern.test(els[i].className)) {
    
          classElements[j] = els[i];
    
          j++;
    
        }
    
      }
    
      return classElements;
    
    }
    
    0 讨论(0)
提交回复
热议问题