DOM CSS



HTML DOM allows JavaScript to change the style of HTML elements.


Change HTML style

To change the style of HTML elements, please use this syntax:

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

The following example will change the style of the <p> element:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<p id="p1">Hello World!</p>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color="blue";
document.getElementById("p2").style.fontFamily="Arial";
document.getElementById("p2").style.fontSize="larger";
</script>
<p>以上段落通过脚本修改。</p>

</body>
</html>

Run instance»

Click the "Run instance" button to view the online instance


Use Events

HTML DOM allows us to execute code by triggering events.

For example, the following events:

  • The element is clicked.

  • The page is loaded.

  • The input box is modified.

  • ……

In the following chapters, you will learn more about the event.

This example changes the style of the HTML element with id="id1" when the user clicks the button:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<h1 id="id1">我的标题 1</h1>
<button type="button" onclick="document.getElementById('id1').style.color='red'">
点我!</button>

</body>
</html>

Run Example»

Click the "Run Example" button to view online examples



More examples

Visibility
How to make an element invisible. Do you want the element to appear or disappear?

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<p id="p1">这是一个文本。 这是一个文本。 这是一个文本。 这是一个文本。 这是一个文本。 这是一个文本。 这是一个文本。</p>
<input type="button" value="隐藏文本" onclick="document.getElementById('p1').style.visibility='hidden'" />
<input type="button" value="显示文本" onclick="document.getElementById('p1').style.visibility='visible'" />

</body>
</html>

Run Instance»

Click the "Run Instance" button to view the online instance