Javascript to get the active li class name

I need to get the class name of the active <li> on different checkout steps on my page as they are called by javascript.

For example:

Step1

<ul class="checkout-bar">
<li class="active first"></li>
<li class="next"></li>
<li class="last"></li>
</ul>

Step2

<ul class="checkout-bar">
<li class="visited first"></li>
<li class="active"></li>
<li class="last"></li>
</ul>

Step3

<ul class="checkout-bar">
<li class="visited first"></li>
<li class="visited "></li>
<li class="active last"></li>
</ul>

So i need to be able to pass to the datalayer at each step:

step1 "active first"

Step2 "active"

Step3 "active last"

I've tried this but it doesn't work:

function() {

var element=document.querySelector('ul.checkout-bar > li');

return element ? element.value : undefined;

}

5 answers

  • answered 2018-04-14 14:29 raul.vila

    You should filter the "li" elements with "active" class and return classList.value:

    function foo() {
        var element=document.querySelector('ul.checkout-bar > li.active');
        return element ? element.classList.value : undefined;
    }
    

  • answered 2018-04-14 14:29 shashikant kuswaha

    you can try this to get the second class name in the class attribute.

    Consider below sample

    <ul class="checkout-bar">
    <li class="active first"></li>
    <li class="next"></li>
    <li class="last"></li>
    </ul>
    
    <script>
     var nam=$('.checkout-bar li.active').attr('class').split(' ')[1];
     console.log(nam); //will return "first" as class name since li having 
               //class active has another class after active is "first" 
    </script>
    

  • answered 2018-04-14 14:29 Mehran Prs

    If you want to get active element classes,content or Dom try this :

    function() {
    
              ‍‍var element=document.querySelector('ul.checkout-bar > li.active');
    
              // If you want class list in string divided by space : 
              var classList= element ? element.classList.toString() : undefined;
    
              // If you want active element ;
              var activeElem=element?element:undefined;
    
              // If want text content of active element :
              var content=element?element.textContent:undefined;
    
              // Return variable that want :
              return classList;
    
    }
    

  • answered 2018-04-14 14:29 Veshraj Joshi

    You missed 1st thing in querySelector is you didnot mention active class. 2nd thing is that you make use of value(no such property in javascript for HTML elements other than input, instead make use of innerText and innerHTML attribute to get required content) and condition. I would like to suggest code like below. But remember querySlector always create an array of element and will always point first element.

     <ul class="checkout-bar">
        <li class="active first">hello1</li>
        <li class="next">hello2</li>
        <li class="last">hello3</li>
    </ul>
    <script>
        alert(activeText());
        function activeText()
        {
            var element=document.querySelector('ul.checkout-bar > li.active');
            return (typeof element != 'undefined')?element.innerText : undefined;
        }
    </script>
    

  • answered 2018-04-14 14:29 zer00ne

    If you need to have the classList of an element, be aware that it is not a String, nor is it an Array, it's a DOMTokenList which is a set of whitespace delimited token (a token apparently is a string without quotes.) The best way to approach one is to think of it as an array-like object with its own set of methods.

    Demo

    Details commented in Demo

    //~~~~~~~~~~~~~~~~~~~~~~~~setActive()~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    /* setActive() function is provided in order to make this Demo interactive. It is not the primary part of the answer, so I will forego the step-by-srep explination. */
    
    /* Anytime a list item is clicked, setActive() will toggle .active class and add the .visited class as well. */
    
    document.querySelector('.checkout-bar').onclick = setActive;
    
    const lis = document.querySelectorAll('li');
    
    function setActive(e) {
      if (e.target.tagName === "LI") {
        for (let i = 0; i < lis.length; i++) {
          lis[i].classList.remove('active');
        }
        e.target.classList.add('active', 'visited');
      }
      console.log(getClasses(".active", items));
    }
    
    //~~~~~~~~~~~~~getClasses(selector, items)~~~~~~~~~~~~~~~~~~~~~~~
    
    /* Create an array of strings that represent the classes you want 
    || to find on any given selector.
    */
    var items = ["active", "visited", "first", "middle", "last"];
    
    /* 1st parameter is a selector of the element you wish to examine
    || 2nd parameter is an array of classes you want to search for
    */
    /* A classList is accessed through the DOMTokenList interface.
    || A DOMTolkenList is not a string nor is it an array, it is a set
    || of tokens delimited by a space. It's best to regard a DTL as an
    || array-like object.
    */
    /* getClasses() function will collect/compare the classList of any
    || given element by a selector (needs to be selector syntax) to an
    || array of classNames. It will return an array of matches.
    */
    function getClasses(selector, items) {
      let node = document.querySelector(selector);
      let list = node.classList;
      var matches = [];
      items.forEach(function(item) {
        if (list.contains(item)) {
          matches.push(item);
        }
      });
      return matches;
    }
    
    var result = getClasses(".active", items);
    
    console.log(result);
    li {
      list-style: none;
      cursor: pointer;
      line-height: 2;
    }
    
    .visited {
      color: tomato
    }
    
    .active {
      background: #333;
      color: #fc0;
    }
    
    
    
    
    /* For Demo Purposes Only */
    
    .as-console-wrapper.as-console-wrapper {
      max-height: 75px
    }
    <ul class="checkout-bar">
      <li class="first">First</li>
      <li class="middle">Middle</li>
      <li class="last active">Last</li>
    </ul>