/    /  Javascript DOM- Nodes

Javascript DOM- Nodes

 

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

 

Example:

 

<!DOCTYPE html>
<html>
<body>

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
</script>

</body>
</html>

 

OUTPUT:

 

This is a paragraph.
This is another paragraph.
This is new.

 

Creating new HTML Elements – insertBefore():

 

Appended the new element as the last child node of the parent.we don’t want that you can use the insertBefore() method:

 

Example:

 

<!DOCTYPE html>
<html>
<body>

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);

var element = document.getElementById("div1");
var child = document.getElementById("p1");
element.insertBefore(para,child);
</script>

</body>
</html>

 

OUTPUT:

 

This is new.
This is a paragraph.
This is another paragraph.

 

Removing Existing HTML Elements:

 

use the remove() method:

 

Example:

 

<!DOCTYPE html>
<html>
<body>

<div>
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<button onclick="myFunction()">Remove Element</button>

<script>
function myFunction() {
 var elmnt = document.getElementById("p1");
 elmnt.remove();
}
</script>

</body>
</html>

 

OUTPUT:

 

node

 

Removing a Child Node:

 

not support the remove() method

 

Example:

 

<!DOCTYPE html>
<html>
<body>

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>

</body>
</html>

 

OUTPUT:

 

This is another paragraph.

 

Replacing HTML Elements :

 

use the replaceChild() method:

 

Example:

 

<!DOCTYPE html>
<html>
<body>

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
parent.replaceChild(para,child);
</script>

</body>
</html>

 

OUTPUT:

 

This is new.
This is another paragraph.