Home > Back-end >  Is there a way to change css selector with javascript?
Is there a way to change css selector with javascript?

Time:01-31

I have a div with 5 elements, and I only want to show 1 at a time. Is there a way to change .classname:nth-child(1) to .classname:nth-child(3) in javascript? Or do I need a different approach? I have a display none on the parent and i want to display flex the nth child

CodePudding user response:

I suppose this different approach may be viable. The snippet uses event delegation:

document.addEventListener(`click`, handle);

function handle(evt) {
  if (evt.target.id === `next`) {
    let next;
    // remove .active from all elements
    document.querySelectorAll(`.className`).forEach(
      (elem, i) => {
        if (elem.classList.contains(`active`)) {
          // Note: nth-child is not zero based
          next = i   2 > 5 ? 1 : i   2; 
        }
        elem.classList.remove(`active`);
      });
    // add .active to the next element 
    document.querySelector(`.className:nth-child(${next})`)
      .classList.add(`active`);
  }
}
.className {
  display: none;
}

.active {
  display: block;
}
<div >div 1</div>
<div >div 2</div>
<div >div 3</div>
<div >div 4</div>
<div >div 5</div>

<button id="next">next</button>

  • Related