skip to Main Content

I want to select the set of <li> elements that come before the one with the "active" class and not that are come after "active" class.

<li></li>
<li></li>
<li></li>
<li></li>

<li class="active"></li>
<li></li>
<li></li>
<li></li>
<li></li>

2

Answers


  1. Use querySelectorAll() to select all the <li> elements into a list. Then filter() that list, searching for the one which is active. Once you find it, set a flag and ignore the rest of the <li> elements.

    let foundIt = false;
    let elements = [...document.querySelectorAll('li')];
    let first = elements.filter(function(e) {
        if ( e.classList.contains('active') ) {
            foundIt = true;
        }
    
        return ! foundIt
    })
    
    console.log(first) // The elements before the "active" one
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    
    <li class="active"></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    Login or Signup to reply.
  2. Here’s how you can select all the elements above the class active in CSS and JS

    FOR your css:

    li:not(.active):not(li.active ~ li) {
        /*you style*/
    }
    

    For your JavaScript:

    const elementsAboveActive = document.querySelectorAll('li:not(.active):not(li.active ~ li)');
    // for example
    elementsAboveActive.forEach((i) => i.style.color = 'aqua');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search