HTML DOM - Modification



Modify HTML = change elements, attributes, styles and events.


Modifying HTML elements

Modifying the HTML DOM means many different things:

  • Changing HTML content

  • Change CSS styles

  • Change HTML attributes

  • Create new HTML elements

  • Delete existing HTML elements

  • Change events (handlers)

In the next chapters, we will learn more about modifying HTML Common methods of DOM.


Creating HTML content

The easiest way to change the content of an element is to use the innerHTML property.

The following example changes the HTML content of a <p> element:

Example

<html><!DOCTYPE html>
<html>
<body>

<p id="p1">Hello World!</p>

<script>
document.getElementById("p1").innerHTML="New text!";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

Run Example»

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

lampWe will explain it to you in the following chapters Details in the example.


Changing HTML Styles

Through the HTML DOM, you can access the style object of an HTML element.

The following example changes the HTML style of a paragraph:

Example

<html><!DOCTYPE html>
<html>
<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>

</body>
</html>

Run Example»

Click the "Run Example" button to view the online example


Create a new HTML element

To add a new element to the HTML DOM, you must first create the element (element node) and then append it to the existing element.

Instance

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

<div id="div1">
<p id="p1">这是一个段落。</p>
<p id="p2">这是另一个段落。</p>
</div>
<script>
var para=document.createElement("p");
var node=document.createTextNode("这是一个新段落。");
para.appendChild(node);
var element=document.getElementById("div1");
element.appendChild(para);
</script>

</body>
</html>

Run instance»

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