JavaScript DOM Style


In JavaScript, you can use the DOM (Document Object Model) to manipulate the styling of HTML elements to change the visualizaton .

Here are some common methods for styling elements using JavaScript:

  1. Changing the CSS style of an element
  2. Adding or removing a CSS class
  3. Setting the CSS style using inline styles

1. Changing the CSS style of an element

You can use the style property of an element to change its CSS style.

Example

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>TutorilsTrend - JavaScript DOM styles Example</h2> 
<h1 id="myElementid">TutorialsTrend</h1> 
<script>
const element = document.getElementById("myElement");
element.style.color = "red";
element.style.backgroundColor = "yellow";
</script>
</body>
</html>

Output

javascript DOM Style

2. Adding or removing a CSS class

You can use the classList property of an element to add or remove a CSS class.

Example

<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.myClass {
color: red;
background-color: yellow;
}

</style>
</head>
<body>
<h2>TutorilsTrend - JavaScript DOM styles 
Example</h2> 
<h1 id="myElementid" class="myClass">TutorialsTrend</h1> 

<script>
const element = document.getElementById("myElementid");

element.classList.add("myClass");
element.classList.remove("myClass");

</script>
</body>
</html>

Output

javascript DOM Style

3. Setting the CSS style using inline styles

You can use the setAttribute method to set the style attribute of an element to a string of CSS styles.

Example

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>

<h2>TutorilsTrend - JavaScript DOM styles Example</h2> 
<h1 
id="myElementid">TutorialsTrend</h1> 
<script>
const element = 
document.getElementById("myElementid");
element.setAttribute("style", "color: 
red; background-color: yellow;");
</script>
</body>
</html>

Output

javascript DOM Style

Note that setting the style attribute using setAttribute will replace any existing styles on the element. If you want to add or modify styles without removing existing ones, you should use the style property instead.


Prev Next