Javascript add style to an element Example

Javascript add style to an element Example; In this tutorial, you will learn how to add css styles to an element using class name in JavaScript DOM methods. More then times we need to add a inline css to a div element for just a time, So we use inline css for that. Many developers nee to add only css style in JS because they are no using jQuery liabrary.

The class name attribute can be used by CSS and JavaScript to perform certain tasks for elements with the specified class name. Below we haved added best methods for adding css style with class in js to a div, p tag, span, label, input etc easy way.

HTML Div Element:

Suppose we have a div element as follows. We can add inline css style using the JavaScript DOM methods or global styles to that element.

<div class="test-content">Element where we want to add css style.</div>

Example 1: Inline styles

Here the first example which will add inline style for your div element. Here first we get the element by using class name. We are using querySelectory to getting the div element. The following code changes the background color and color of the <div> element above:

const testContent = document.querySelector('.test-content');
testContent.style.backgroundColor = 'yellow';
testContent.style.color = 'red';

Example 2: Using cssText property

The second way we can add the multiple css style to a div element in javascript using the cssText property. Here we used the += operator to append new styles to the existing ones.

const testContent = document.querySelectory('.test-content');
testContent.style.cssText += 'color:red;background-color:yellow';

Next we can use the below as well, but = operator, the existing style will be removed, like this:

const testContent = document.querySelectory('.test-content');
testContent.style.cssText = 'color:red;background-color:yellow';

Example 3: Using a helper function

The following helper function accepts an element and a style object. It add all styles from the style object to the style property of the element and we can use this css() helper function to set the styles for the element as follows.

<script>
    const testContent = document.querySelector('.test-content');
    addCss(testContent, {
        'background-color': 'yellow',
        color: 'red'
    });

    function addCss(element, style) {
        for (const property in style)
            element.style[property] = style[property];
    }
</script>

I hope you enjoy with add css style to an element using class name in javascript, for more follow us social networks.

Leave a Comment