HTML DOM allows JavaScript to change the style of HTML elements.
Below is the syntax to modify the style of an html element using JavaScript style properties.
Syntax:
Object.style.property=new style;
Take a look at the code below:
We used JavaScript to Change the style of the <p> element.
- Change the color to
white
. - Font size to
40px
. - Background color to
tomato
:
<p id="pcon">Hello World!</p>
<script>
var mychar = document.getElementById("pcon");
mychar.style.color = "white";
mychar.style.fontSize = "40px";
mychar.style.backgroundColor = "tomato";
</script>
result:
Task - Exercise 19
Now let's change the CSS style of the element in the HTML:
1. Supply the code on line 12, modify the style of the h2 tag, and set the color to red.
2. Supply the code on line 13, modify the style of the h2 tag, and set the background color to gray (#CCC).
3.Supply the code on line 14, modify the style of the h2 tag, and set the width to 300px.
Task Code
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>style</title>
</head>
<body>
<h2 id="con">I love JavaScript</H2>
<script type="text/javascript">
var mychar = document. getElementById("con");
</script>
</body>
</html>
//= htmlentities($post["body"]); ?>