how to change style with js code example
Example 1: how to change style of an element using javascript
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
Example 2: change color of css in js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Change the Background Color with JavaScript</title>
<script>
function changeBodyBg(color){
document.body.style.background = color;
}
function changeHeadingBg(color){
document.getElementById("heading").style.background = color;
}
</script>
</head>
<body>
<h1 id="heading">This is a heading</h1>
<p>This is a paragraph of text.</p>
<hr>
<div>
<label>Change Webpage Background To:</label>
<button type="button" onclick="changeBodyBg('yellow');">Yellow</button>
<button type="button" onclick="changeBodyBg('lime');">Lime</button>
<button type="button" onclick="changeBodyBg('orange');">Orange</button>
</div>
<br>
<div>
<label>Change Heading Background To:</label>
<button type="button" onclick="changeHeadingBg('red');">Red</button>
<button type="button" onclick="changeHeadingBg('green');">Green</button>
<button type="button" onclick="changeHeadingBg('blue');">Blue</button>
</div>
</body>
</html>
Example 3: change style js
// select element from DOM
const el = document.querySelector('.para')
// change css style
el.style.color = 'purple'