html

Set CSS Property in JavaScript

JavaScript is one of the core scripting languages and technologies of the world wide web. It is a dynamically executing programming language. CSS is the language used to control the styling of the documents written in markup languages like HTML and XHTML.

CSS properties can be applied to a code written in JavaScript in an HTML document easily by accessing the element on which the property has to be applied through JavaScript and directly applying the CSS property on it.

Setting CSS Property in JavaScript

Let’s take an example of a simple HTML code to format the JavaScript document:

<h3 id="text"> Click OK to change my color </h3>
      <button type="button">OK</button>
      <p id="demo"></p>

In the above code snippet, there is a heading that we assigned an id “test”. Below that, we created a button “OK” through the button tag and declared the “onclick” function for that button. This specifies that when the “OK” button will be clicked, the “Func()” JavaScript function will be invoked and the CSS property defined inside that function will be implemented to the text written in HTML.

Following is a JavaScript function to make the above HTML code dynamically executable:

function Func() {
  var y = document.getElementById("text");
  y.style.color = "red";
}

The above code snippet has a function named “Func()” in which a variable “y” is initialized and the “getElementById” method is declared to refer to the “text” id that has the text (content). Then, there is the CSS property inserted to change the color of the text to red.

This will display a text in the output interface that on clicking the OK button will change the color of the text to red:

In this way, we can set CSS properties in JavaScript.

Conclusion

We can set CSS properties in an element in JavaScript by first accessing the id, class, or attribute of that element by using the relevant get method. For instance, in the above post, we applied the “getElementById” method. After that, simply define the CSS property to be applied to that element. This article explained well how to set CSS properties in JavaScript.

About the author

Hadia Atiq

A Software Engineer and Technical Writer passionate about learning and spreading knowledge of the latest technology. I utilize my writing skills to help readers understand the importance and usage of modern technology.