Home > Mobile >  HTML apply class on each elemnts from class to another class
HTML apply class on each elemnts from class to another class

Time:01-12

I need to create a function that will adding specific class depending on the following condition :

a div class contain the "start" class, so all nexting div / element will receive a new class on it until there is the div class that contain "end" class

Quick example:

<div></div> // no need
<div class='start'></div>
<div></div> // need to add class on it
<div></div> // need to add class on it
<div></div> // need to add class on it
<div class='end'></div>
<div></div> // no need

Final result:

<div></div>
<div class='start'></div>
<div ></div>
<div ></div>
<div ></div>
<div class='end'></div>
<div></div>

I'm struggling with this because all div neeed to be at the same level

CodePudding user response:

You need to use .nextElementSibling ! You can create something like

const applyClassFromStartToEndOnElements = (
  startClassName,
  endClassName,
  classNameToApply
) => {
  const startElement = document.querySelector(`.${startClassName}`)

  let nextElem = startElement
  if (startElement) {
    nextElem = startElement.nextElementSibling
    while (nextElem && !Array.from(nextElem.classList).includes(endClassName)) {
      nextElem.className = `${classNameToApply} ${nextElem?.className}`
      nextElem = nextElem.nextElementSibling
    }
  }
};

applyClassFromStartToEndOnElements("start", "end", "new-class")

You also need to check if the next element is existing (!== undefined), since while can be infinity !

code

  • Related