How to apply CSS class in Javascript?

Duomly - Aug 7 '20 - - Dev Community

This post was originally published at https://www.blog.duomly.com/6-most-popular-front-end-interview-questions-and-answers-for-beginners-part-3/#how-to-apply-css-class-in-javascript


DOM manipulation is definitely the skill that you need to have if you’d like to be a successful front-end developer, especially if you’d like to work with UI, as for example, UI developer.

Whole DOM manipulation is a huge topic, and I’ll be showing you the most popular methods in time to time in the Front-End Interview Questions series.

Especially in PART 3, we’ll talk about that even a few times.

Whole DOM manipulation is a kind of resource-hungry stuff, and if you can, you should go forward with the stuff like virtual DOM, but sometimes you need to do it with the normal DOM anyway.

In the previous section, I’ve shown you how you can manipulate with classes by using jQuery, but what if you don’t want to use jQuery in your project, and you need to do it with pure JS?

You need to know how to do it!

Let’s see on the code example.

As the first step, we need to select the element that we’d like to modify.

In this case, I’ve added an id to the element that is kind of comfortable to select, because the method “getElementById” returns only one element.

Next, when we have selected elements, we can use the method “setAttribute” and define attribute type as “class”, the value we can setup however we want.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Learn coding on Duomly.com</title>
  </head>
  <body>
    <div id="hero">
      This is hero element
    </div>
    <script>
      const hero = document.getElementById("hero");
      hero.setAttribute("class", "rounded");
    </script>
  </body>
</html>

Duomly - Programming Online Courses

Thank you for reading,
Radek from Duomly

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .