Styling with CSS classes in JavaScript

In the previous lesson, we learned how to change the CSS styles of elements by changing the style attribute. More often than not, this is not a good idea. The fact is that if you scatter CSS styles over JavaScript code, it will be problematic to change the design of the site in the future, since you will have to pick the JavaScript code in search of styles hardcoded there.

More convenient for future support would be to add or remove CSS classes to the element, thereby styling them as needed.

Let's look at an example. Let's have a few paragraphs:

<p>text1</p> <p>text2</p> <p>text3</p>

Let's make it so that when you click on any paragraph, this paragraph is painted in some color, for example, in green. To do this, in the CSS file we will make a special class for coloring paragraphs:

.colored { color: green; }

The advantage of using a class is that now it will be easy to change the desired color - for this you will just need to make a change to the CSS file, without picking the JavaScript code. This will be especially convenient if you write the JavaScript code, and in the future someone else will style it (perhaps a less qualified person who can only work with CSS).

So, now, after introducing the class, by clicking on any paragraph, you can change its color by simply adding our class to it:

let elems = document.querySelectorAll('p'); for (let elem of elems) { elem.addEventListener('click', function() { this.classList.add('colored'); // adds the class to the paragraph }); }

Explain why I chose the word colored for the class name, and not the word green, which clearly indicates the color we want.

Given a paragraph. Given buttons 'cross out', 'make bold', 'make red'. Let on clicking on each button the given action happens to the paragraph (becomes red, for example).

enru