Get in touch with our hands-on, fast and professional Support Team

  • This topic is empty.
Viewing 15 posts - 16 through 30 (of 31 total)
  • Author
    Posts
  • #9684

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
    David Hoang
    Keymaster

    Just thought I’d throw this in:

    function inArray(val, ary){
      for(var i=0,l=ary.length; i<l; i++){
        if(ary[i] === val){
          return true;
        }
      }
      return false;
    }
    function removeClassName(classNameS, fromElement){
      var x = classNameS.split(/\s/), s = fromElement.className.split(/\s/), r = [];
      for(var i=0,l=s.length; i<l; i++){
        if(!iA(s[i], x))r.push(s[i]);
      }
      fromElement.className = r.join(' ');
    }
    function addClassName(classNameS, toElement){
      var s = toElement.className.split(/\s/);
      s.push(c); toElement.className = s.join(' ');
    }
    
    #9697

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
    David Hoang
    Keymaster

    Here’s a toggleClass to toggle/add/remove a class on an element:

    // If newState is provided add/remove theClass accordingly, otherwise toggle theClass
    function toggleClass(elem, theClass, newState) {
        var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');
        var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null));
    
        elem.className=elem.className.replace(matchRegExp, ''); // clear all
        if (add) elem.className += ' ' + theClass;
    }
    

    See the JSFiddle.

    Also see my answer here for creating a new class dynamically.

    #9699

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
    David Hoang
    Keymaster

    Change an element’s class in vanilla JavaScript with Internet Explorer 6 support

    You may try to use the node attributes property to keep compatibility with old browsers, even Internet Explorer 6:

    function getClassNode(element) {
      for (var i = element.attributes.length; i--;)
        if (element.attributes[i].nodeName === 'class')
          return element.attributes[i];
    }
    
    function removeClass(classNode, className) {
      var index, classList = classNode.value.split(' ');
      if ((index = classList.indexOf(className)) > -1) {
        classList.splice(index, 1);
        classNode.value = classList.join(' ');
      }
    }
    
    function hasClass(classNode, className) {
      return classNode.value.indexOf(className) > -1;
    }
    
    function addClass(classNode, className) {
      if (!hasClass(classNode, className))
        classNode.value += ' ' + className;
    }
    
    document.getElementById('message').addEventListener('click', function() {
      var classNode = getClassNode(this);
      var className = hasClass(classNode, 'red') && 'blue' || 'red';
    
      removeClass(classNode, 'red');
      removeClass(classNode, 'blue');
    
      addClass(classNode, className);
    })
    .red {
      color: red;
    }
    .red:before {
      content: 'I am red! ';
    }
    .red:after {
      content: ' again';
    }
    .blue {
      color: blue;
    }
    .blue:before {
      content: 'I am blue! '
    }
    <span id="message" class="">Click me</span>
    #9685

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
    David Hoang
    Keymaster

    Just use myElement.classList="new-class" unless you need to maintain other existing classes in which case you can use the classList.add, .remove methods.

    var doc = document;
    var divOne = doc.getElementById("one");
    var goButton = doc.getElementById("go");
    
    goButton.addEventListener("click", function() {
      divOne.classList="blue";
    });
    div{
      min-height: 48px;
      min-width: 48px;
    }
    .bordered{
      border: 1px solid black;
    }
    .green{
      background: green;
    }
    .blue{
      background: blue;
    }
    <button id="go">Change Class</button>
    
    <div id="one" class="bordered green">
    
    </div>
    #9691

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
    David Hoang
    Keymaster

    OK, I think in this case you should use jQuery or write your own Methods in pure JavaScript. My preference is adding my own methods rather than injecting all jQuery to my application if I don’t need that for other reasons.

    I’d like to do something like below as methods to my JavaScript framework to add few functionalities which handle adding classes, deleting classes, etc. Similar to jQuery, this is fully supported in IE9+. Also my code is written in ES6, so you need to make sure your browser support it or you using something like Babel, otherwise need to use ES5 syntax in your code. Also in this way, we finding element via ID, which means the element needs to have an ID to be selected:

    // Simple JavaScript utilities for class management in ES6
    var classUtil = {
    
      addClass: (id, cl) => {
        document.getElementById(id).classList.add(cl);
      },
    
      removeClass: (id, cl) => {
        document.getElementById(id).classList.remove(cl);
      },
    
      hasClass: (id, cl) => {
        return document.getElementById(id).classList.contains(cl);
      },
    
      toggleClass: (id, cl) => {
        document.getElementById(id).classList.toggle(cl);
      }
    
    }
    

    And you can simply use them as below. Imagine your element has id of ‘id’ and class of ‘class’. Make sure you pass them as a string. You can use the utility as below:

    classUtil.addClass('myId', 'myClass');
    classUtil.removeClass('myId', 'myClass');
    classUtil.hasClass('myId', 'myClass');
    classUtil.toggleClass('myId', 'myClass');
    
    #9689

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
    David Hoang
    Keymaster

    classList DOM API:

    A very convenient manner of adding and removing classes is the classList DOM API. This API allows us to select all classes of a specific DOM element in order to modify the list using JavaScript. For example:

    const el = document.getElementById("main");
    console.log(el.classList);
    <div class="content wrapper animated" id="main"></div>

    We can observe in the log that we are getting back an object with not only the classes of the element, but also many auxiliary methods and properties. This object inherits from the interface DOMTokenList, an interface which is used in the DOM to represent a set of space separated tokens (like classes).

    Example:

    const el = document.getElementById('container');
    
    function addClass () {
        el.classList.add('newclass');
    }
    
    
    function replaceClass () {
        el.classList.replace('foo', 'newFoo');
    }
    
    
    function removeClass () {
        el.classList.remove('bar');
    }
    button{
      margin: 20px;
    }
    
    .foo{
      color: red;
    }
    
    .newFoo {
      color: blue;
    }
    
    .bar{
      background-color: powderblue;
    }
    
    .newclass{
      border: 2px solid green;
    }
    <div class="foo bar" id="container">
      "Sed ut perspiciatis unde omnis
      iste natus error sit voluptatem accusantium doloremque laudantium,
      totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et
      quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam
      voluptatem quia voluptas
     </div>
    
    <button onclick="addClass()">AddClass</button>
    
    <button onclick="replaceClass()">ReplaceClass</button>
    
    <button onclick="removeClass()">removeClass</button>
    #9690

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
    David Hoang
    Keymaster

    Yes, there are many ways to do this. In ES6 syntax we can achieve easily. Use this code toggle add and remove class.

    const tabs=document.querySelectorAll('.menu li');
    
    for(let tab of tabs){
    
      tab.onclick = function(){
    
        let activetab = document.querySelectorAll('li.active');
    
        activetab[0].classList.remove('active')
    
        tab.classList.add('active');
      }
    
    }
    body {
        padding: 20px;
        font-family: sans-serif;
    }
    
    ul {
        margin: 20px 0;
        list-style: none;
    }
    
    li {
        background: #dfdfdf;
        padding: 10px;
        margin: 6px 0;
        cursor: pointer;
    }
    
    li.active {
        background: #2794c7;
        font-weight: bold;
        color: #ffffff;
    }
    <i>Please click an item:</i>
    
    <ul class="menu">
      <li class="active"><span>Three</span></li>
      <li><span>Two</span></li>
      <li><span>One</span></li>
    </ul>
    #9686

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
    David Hoang
    Keymaster

    TL;DR:

    document.getElementById('id').className = 'class'
    

    OR

    document.getElementById('id').classList.add('class');
    document.getElementById('id').classList.remove('class');
    

    That’s it.

    And, if you really want to know the why and educate yourself then I suggest reading Peter Boughton’s answer. It’s perfect.

    Note:

    This is possible with (document or event):

    • getElementById()
    • getElementsByClassName()
    • querySelector()
    • querySelectorAll()
    #9692

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
    David Hoang
    Keymaster

    Try:

    element.className='second'
    
    function change(box) { box.className='second' }
    .first  { width:  70px; height:  70px; background: #ff0                 }
    .second { width: 150px; height: 150px; background: #f00; transition: 1s }
    <div onclick="change(this)" class="first">Click me</div>
    #9693

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
    David Hoang
    Keymaster

    THE OPTIONS.

    Here is a little style vs. classList examples to get you to see what are the options you have available and how to use classList to do what you want.

    style vs. classList

    The difference between style and classList is that with style you’re adding to the style properties of the element, but classList is kinda controlling the class(es) of the element (add, remove, toggle, contain), I will show you how to use the add and remove method since those are the popular ones.


    Style Example

    If you want to add margin-top property into an element, you would do in such:

    // Get the Element
    const el = document.querySelector('#element');
    
    // Add CSS property 
    el.style.margintop = "0px"
    el.style.margintop = "25px" // This would add a 25px to the top of the element.
    

    classList Example

    Let say we have a <div class="class-a class-b">, in this case, we have 2 classes added to our div element already, class-a and class-b, and we want to control what classes remove and what class to add. This is where classList becomes handy.

    Remove class-b

    // Get the Element
    const el = document.querySelector('#element');
    
    // Remove class-b style from the element
    el.classList.remove("class-b")
    
    

    Add class-c

    // Get the Element
    const el = document.querySelector('#element');
    
    // Add class-b style from the element
    el.classList.add("class-c")
    
    

    #9687

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
    David Hoang
    Keymaster
    function classed(el, class_name, add_class) {
      const re = new RegExp("(?:^|\\s)" + class_name + "(?!\\S)", "g");
      if (add_class && !el.className.match(re)) el.className += " " + class_name
      else if (!add_class) el.className = el.className.replace(re, '');
    }
    

    Using Peter Boughton’s answer, here is a simple cross-browser function to add and remove class.

    Add class:

    classed(document.getElementById("denis"), "active", true)
    

    Remove class:

    classed(document.getElementById("denis"), "active", false)
    
    #9688

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
    David Hoang
    Keymaster

    There is a property, className, in JavaScript to change the name of the class of an HTML element. The existing class value will be replaced with the new one, that you have assigned in className.

    <!DOCTYPE html>
    <html>
    <head>
    <title>How can I change the class of an HTML element in JavaScript?</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    </head>
    <body>
    <h1 align="center"><i class="fa fa-home" id="icon"></i></h1><br />
    
    <center><button id="change-class">Change Class</button></center>
    
    <script>
    var change_class = document.getElementById("change-class");
    change_class.onclick = function()
    {
        var icon=document.getElementById("icon");
        icon.className = "fa fa-gear";
    }
    </script>
    </body>
    </html>
    

    Credit – How To Change Class Name of an HTML Element in JavaScript

    #9695

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
    David Hoang
    Keymaster

    The OP question was How can I change an element’s class with JavaScript?

    Modern browsers allow you to do this with one line of JavaScript:

    document.getElementById('id').classList.replace('span1', 'span2')

    The classList attribute provides a DOMTokenList which has a variety of methods. You can operate on an element’s classList using simple manipulations like add(), remove() or replace(). Or get very sophisticated and manipulate classes like you would an object or Map with keys(), values(), and entries().

    Peter Boughton’s answer is a great one, but it’s now over a decade old. All modern browsers now support DOMTokenList – see https://caniuse.com/#search=classList and even Internet Explorer 11 supports some DOMTokenList methods.

    #9707

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
    David Hoang
    Keymaster

    4 actions possible: Add, Remove, Check, and Toggle

    Let’s see multiple ways for each action.

    1. Add class

    Method 1: Best way to add a class in the modern browser is using classList.add() method of element.

    • Case 1: Adding single class

      function addClass() {
        let element = document.getElementById('id1');
      
        // adding class
        element.classList.add('beautify');
      }
      
    • Case 2: Adding multiple class

      To add multiple classes saperate classes by a comma in the add() method

      function addClass() {
        let element = document.getElementById('id1');
      
        // adding multiple class
        element.classList.add('class1', 'class2', 'class3');
      }
      

    Method 2 – You can also add classes to HTML elements using className property.

    • Case 1: Overwriting pre-existing classes
      When you assign a new class to the className property it overwrites the previous class.

      function addClass() {
        let element = document.getElementById('id1');
      
        // adding multiple class
        element.className = 'beautify';
      }
      
    • Case 2: Adding class without overwrite
      Use += operator for class not to overwrite previous classes. Also, add an extra space before the new class.

      function addClass() {
        let element = document.getElementById('id1');
      
        // adding single multiple class
        element.className += ' beautify';
        // adding multiple classes
        element.className += ' class1 class2 class3';
      }
      

    2. Remove class

    Method 1 – The best way to remove a class from an element is the classList.remove() method.

    • Case 1: Remove single class

      Just pass the class name you want to remove from the element in the method.

      function removeClass() {
        let element = document.getElementById('id1');
      
        // removing class
        element.classList.remove('beautify');
      }
      
    • Case 2: Remove multiple class

      Pass multiple classes separated by a comma.

      function removeClass() {
        let element = document.getElementById('id1');
      
        // removing class
        element.classList.remove('class1', 'class2', 'class3');
      }
      

    Method 2 – You can also remove class using className method.

    • Case 1: Removing single class
      If the element has only 1 class and you want to remove it then just assign an empty string to the className method.

      function removeClass() {
        let element = document.getElementById('id1');
      
        // removing class
        element.className = '';
      }
      
    • Case 2: Removing multiple class
      If the element has multiple classes first get all classes from the element using the className property and use replace method and replace desired classes with an empty string and finally assign it to element’s className property.

      function removeClass() {
        let element = document.getElementById('id1');
      
        // removing class
        element.className = element.className.replace('class1', '');
      }
      

    3. Checking class

    To check if a class exists in the element you can simply use classList.contains() method. It returns true if the class exists else returns false.

    function checkClass() {
      let element = document.getElementById('id1');
    
      // checking class
      if(element.classList.contains('beautify') {
          alert('Yes! class exists');
      }
    }
    

    4. Toggle class

    To toggle a class use classList.toggle() method.

    function toggleClass() {
        let element = document.getElementById('id1');
    
        // toggle class
        element.classList.toggle('beautify');
    }
    
    #9694

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131

    Deprecated: Function seems_utf8 is deprecated since version 6.9.0! Use wp_is_valid_utf8() instead. in /home/u337135316/domains/bzotech.com/public_html/wp-includes/functions.php on line 6131
    David Hoang
    Keymaster

    For IE v6-9 (in which classList is not supported and you don’t want to use polyfills):

    var elem = document.getElementById('some-id');
    
    // don't forget the extra space before the class name
    var classList = elem.getAttribute('class') + ' other-class-name';
    
    elem.setAttribute('class', classList);
    
Viewing 15 posts - 16 through 30 (of 31 total)
  • You must be logged in to reply to this topic.