Im doing a project, when you click on a divison, the background color is switching to black, and there is a text which appears. This text is from the Javascript because i've 98 divs like that so it is doing it for each div with one function. But i was wondering if we can actually do a CSS class for this text without the HTML. Here is my code so you can understand :
function x1(e) {
var target = e.target, count = +target.dataset.count;
target.style.backgroundColor = count === 1 ? "#707070" : 'black';
target.dataset.count = count === 1 ? 0 : 1;
target.innerHTML = count === 1 ? '' : 'réserver';
}
I wanna add a font-style, font-size, change color, and change position of the text. Can i do it in the javascript ? for all my divs ? Thank you guys, I hope you will understand because my english is sometimes not really good. Have a good day, Cordially, Zartex.
element.classList.add("mystyle")
Javascript has the function classList() for this purpose. Here you can attach functions like:
obj.classList.remove('className');
obj.classList.add('className');
obj.classList.toggle('className');
Basically, they are a wrapper for the getAttribute() function. To understand what is under the hood small example:
short excursus
const d = document.querySelector('div');
// fetch current classes
const classes = d.getAttribute('class');
// set current classes and new class
d.setAttribute('class', classes + " hotpink");
div {
height:80px;
}
.green {
background: green;
}
.hotpink {
background: hotpink;
}
.box {
width: 50%
}
<div class="green box">Current class is green & box but it will overwritten by hotpink which is added</div>
As the previous answer (from abhishek sahu) suggest you can use:
target.classList.add('yourClass');
But, i guesss it's your case, if you want to add and remove the class on every click (so for example you want to click once and add the class and when you click again remove it from the same element) you can use:
target.classList.toggle('yourClass');
The toggle method add a class on an alement if it does't have it already, if so it removes that class