loading...
Cover image for How to add CSS dynamically in Javascript?

How to add CSS dynamically in Javascript?

duomly profile image Duomly Originally published at blog.duomly.com ・2 min read

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-add-css-dynamically-in-javascript


In the previous sections, you could learn how to manipulate with dom in a very simple way.

Like, we created a simple HTML element and created a script that was adding class to the element when the script loads.

We did it in two ways: jQuery (still alive, and still worth to know at least basics!), and the second one you learned is the DOM manipulation with pure JS.

In this section, we will go a bit more advanced.

You will learn how to do DOM manipulation related to the event. In this case, we’ll use the onclick method that we add to the button.

We can specify what element should be selected, by adding the “id” param to the function, and we’ll be able to specify the class name that should be added to the element.

Take a look at the code example that I’ve created for you.

We have here element with id “hero” and button that can fire the “addClass” function with the “onclick” attribute.

Next, we have a js script where we specified function named “addClass” that can take “id”, and “className” as params.

Inside the function, we iterate DOM to find an element with the id that we passed in button and add a class attribute with a class name that we added when fire “addClass” function.

<!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>
    <button onclick="addClass('hero', 'rounded')">Add class</button>
    <script>
      function addClass(id, className) {
        const element = document.getElementById(id);
        element.setAttribute("class", className);
      }
    </script>
  </body>
</html>

Duomly - Programming Online Courses

Thank you for reading,
Radek from Duomly

Posted on by:

duomly profile

Duomly

@duomly

We believe everyone can learn how to code, so we are making learning fun and easy!

Discussion

markdown guide