My initial problem is that I want to put custom colours on my main menu titles. I have done this by using the title + attribute in the CSS. However I don't want the title attribute to appear when hovered over. So I had another idea and wondered if it was possible to add a class (with JS) to a specific text? And if so how to do it?
Each menu title has the following structure:
<span class="menu-text">Random text</span>
They all have the "menu-text" class and that's why I'm trying to differentiate them. In order to apply a different colour.
Thank you in advance for your answers!
This illustrates a simple way to add a class to an element when it is clicked.
window.addEventListener("load", function(){
// gets the elements with the classname .menu-text in a nodeList
const getAllElements = document.querySelectorAll('.menu-text');
for (let item of getAllElements) {
// iterates over all of them, and attaches an event
item.addEventListener('click', function () {
// adds the class .has-background-red
this.classList.add('has-background-red');
});
}
});
.container {
/* just for visual purposes */
display: flex;
gap: 16px;
}
.has-background-red {
background-color: red;
}
<div class="container">
<span class="menu-text">Random text</span>
<span class="menu-text">Random text</span>
<span class="menu-text">Random text</span>
<span class="menu-text">Random text</span>
<span class="menu-text">Random text</span>
<span class="menu-text">Random text</span>
<span class="menu-text">Random text</span>
<span class="menu-text">Random text</span>
<span class="menu-text">Random text</span>
</div>