Home > Back-end >  I have a this slider, but I want a add div background color after a .current class div (3rd one)
I have a this slider, but I want a add div background color after a .current class div (3rd one)

Time:03-29

<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>

I have a this slider, but I want a add div background color after a .current class div (3rd one).

CodePudding user response:

So if you just want to add a background color to the third div, you can add a simple script to solve this. Here is an example:

document.getElementsByClassName('slider')[2].style.background = "red";

CodePudding user response:

You can use nextSibling like so:

document.querySelector('.slider').nextSibling.style.backgroundColor = 'red';

CodePudding user response:

Here one approach using CSS, HTML and vanilla JavaScript to highlight the currently selected div. You can select the div by clicking on it.

One could also implement a solution using event bubbling.

function setCurrent(newCurrent) {
  // select the currently active div
  const current = document.querySelector(".slider.current");
  // if it's the one that's already active, there is nothing to do
  if (newCurrent == current) return
  // we need to change the currently selected div
  // remove "current" class and update text of current div
  current.classList.remove("current");
  current.textContent = "Slider";
  // add "current" class and set text for now current div
  newCurrent.classList.add("current")
  newCurrent.textContent = "Current";
}

window.addEventListener("DOMContentLoaded", event => {
  // add on click listener to all elements with the a class "slider"
  document.querySelectorAll(".slider").forEach((slider) => {
    slider.addEventListener("click", () => setCurrent(slider));
  })
})
.slider {
  background-color: black;
  color: white;
}


/* more specific rule for elements with class slider and current*/

.slider.current {
  background-color: blue;
}
<div >Slider</div>
<div >Current</div>
<div >Slider</div>
<div >Slider</div>
<div >Slider</div>
<div >Slider</div>

CodePudding user response:

No JavaScript necessary. Just use CSS with .slider.current .slider to select the div after the one with .current

Example:

.slider.current .slider {
  background: red;
}
<div >slider</div>
<div >slider current</div>
<div >slider</div>
<div >slider</div>
<div >slider</div>
<div >slider</div>

  • Related