How can I check if a class exists already on my html element? for e.g. if it already has first,second or third then I want to replace it with the one that I am passing.
Instead of doing like this which is wrong
initHeader(classNames[0])
initHeader(classNames[1])
initHeader(classNames[0])
const banner = document.querySelector('header');
const classNames = [{
image_url: "first"
},
{
image_url: "second"
},
{
image_url: "third"
}
]
function initHeader(bg) {
//check if one of the classes already exists on banner, if yes replace it, if not just add.
banner.classList.add(`${bg.image_url}`)
}
initHeader(classNames[0])
initHeader(classNames[1])
initHeader(classNames[0])
.first {
background-image: url('https://www.investmentmonitor.ai/wp-content/uploads/sites/7/2021/10/Warsaw-skyline-2-934x657-1.jpg');
}
.second{
background-image: url('https://i.natgeofe.com/k/04665f4a-3f8d-4b62-8ca3-09ce7dfc5a20/france-eiffel-tower_4x3.jpg');
}
header {
background-size: cover;
background-position: center;
height: 300px;
width: 100%;
}
<header></header>
>Solution :
If I understand correctly, you want the initHeader
function to leave the banner with only one class at the end of it, right?
You can basically remove all 3, and add the relevant one:
function initHeader(bg) {
banner.classList.remove("first", "second", "third");
banner.classList.add(`${bg.image_url}`);
}
Or, you can check if each one exists before removing (no real difference here)
div.classList.contains("foo")
function initHeader(bg) {
const classes = banner.classList;
if (classes.contains("first") classes.remove("first");
//...similar for rest...
classes.add(`${bg.image_url}`);
}