'I have a this slider, but I want a add div background color after a .current class div (3rd one)
<div class="slider"></div>
<div class="slider current"></div>
<div class="slider"></div>
<div class="slider"></div>
<div class="slider"></div>
<div class="slider"></div>
I have a this slider, but I want a add div background color after a .current class div (3rd one).
Solution 1:[1]
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 class="slider">slider</div>
<div class="slider current">slider current</div>
<div class="slider">slider</div>
<div class="slider">slider</div>
<div class="slider">slider</div>
<div class="slider">slider</div>
Solution 2:[2]
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";
Solution 3:[3]
You can use nextSibling like so:
document.querySelector('.slider').nextSibling.style.backgroundColor = 'red';
Solution 4:[4]
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 class="slider">Slider</div>
<div class="slider current">Current</div>
<div class="slider">Slider</div>
<div class="slider">Slider</div>
<div class="slider">Slider</div>
<div class="slider">Slider</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | j08691 |
| Solution 2 | Ctac |
| Solution 3 | Mystical |
| Solution 4 |
