1

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.

DecPK
  • 24,537
  • 6
  • 26
  • 42
Zartex
  • 13
  • 5
  • You should add [minimal reproducible code](https://stackoverflow.com/help/minimal-reproducible-example), so that people can understand your problem clearly. – DecPK Dec 17 '21 at 10:27
  • See this: [How to dynamically create CSS class in JavaScript and apply?](https://stackoverflow.com/questions/1720320/how-to-dynamically-create-css-class-in-javascript-and-apply) and this: [How can I change an element's class with JavaScript?](https://stackoverflow.com/questions/195951/how-can-i-change-an-elements-class-with-javascript) – aerial Dec 17 '21 at 10:34

3 Answers3

4
element.classList.add("mystyle")
abhishek sahu
  • 648
  • 4
  • 8
1

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

eroironico
  • 1,159
  • 1
  • 15
1

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>
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79