JavaScript HTML DOM change CSS
HTML DOM allows JavaScript to change the style of HTML elements.
Change HTML styles
To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=新样式
The following example will change the style <p> element:
Examples
<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "utf-8">
<Title> This tutorial (w3big.com) </ 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> script by modifying the above paragraphs. </ P>
</ Body>
</ Html>
try it"
Use Event
HTML DOM allows us to execute code by triggering events.
For example, the following events:
- Element is clicked.
- The page loads.
- Input box is modified.
- ......
In the following sections, you will learn more about the event knowledge.
This example changes the style id = "id1" HTML element, when the user clicks the button:
Examples
<! DOCTYPE html>
<Html>
<Body>
<H1 id = "id1"> My heading 1 </ h1>
<Button type = "button"
onclick = "document.getElementById ( 'id1'). style.color = 'red'">
Point me! </ Button>
</ Body>
</ Html>
<Html>
<Body>
<H1 id = "id1"> My heading 1 </ h1>
<Button type = "button"
onclick = "document.getElementById ( 'id1'). style.color = 'red'">
Point me! </ Button>
</ Body>
</ Html>
try it"
More examples
Visibility
How to make an element invisible. Element you want to show or disappear?