JavaScript HTML DOM CSS

Back to JS page

Table of Contents

Changing HTML Style

To change the style of an HTML element, use this syntax:

document.getElementById(id).style.property = new style

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM CSS</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Changing HTML Style</h4>
<p id="demo">This text will change color!</p>

<script>
document.getElementById("demo").style.color = "red";
</script>

</body>
</html>

Example 1

Result View Example

Using Events

The HTML DOM allows you to execute code when an event occurs. Events are generated by the browser when "things happen" to HTML elements.

You can change the style of an element when a user clicks a button:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM CSS</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Using Events</h4>
<p id="demo">Click the button to change style!</p>
<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>

</body>
</html>

Example 2

Result View Example

More Examples

You can change multiple style properties and make elements appear/disappear:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM CSS</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>More Examples</h4>
<p id="demo" style="display:block">This paragraph will disappear</p>

<button type="button" onclick="document.getElementById('demo').style.display='none'">Hide text</button>
<button type="button" onclick="document.getElementById('demo').style.display='block'">Show text</button>

</body>
</html>

Example 3

Result View Example

Document

Document in project

You can Download PDF file.

Reference