fbpx

Dom Manipulation JavaScript

Many developers confuse about the Dom Manipulation so today we will discuss Dom Manipulation using JavaScript, replacing and removing old nodes

Create a new Page

There are two types of website.

  • Static Website
  • Dynamic Website

For the Dom Manipulation In a static website, data is added directly in HTML tags, but in dynamic changing website or web application data is dynamic coming for Server side through JavaScript

JavaScript function like createElement()‎and createTextNode()‎ are used to create a new node element in the Dom.

Let’s have a look at some functions for Dom Manipulation

Property / childDescription
createElement()‎Create a new Element node of an item type
createTextNode()‎Create a new node element of type text
node.textContentAccess or modify the text content of the item node element
node.innerHTMLAccess or modify the HTML content in the item

First of all, create a project Folder with any name I use “Domani”. 

Steps to create the Index.Html

Right click on the empty space in the folder and select New–>Text DocumentNow Go to view then check “filename extensions

After this rename the file as “index.html” and click yes.

Right Click the file and open with Note Pad.

Now add the following code and save the file.

<! DOCTYPE html> <html lang = "en" >
<head> <title> Dom Manipulation JavaScript </ title> </ head>
<body> <h1> Document Object Model </ h1> </ body>
</ html>

Access Dom Elements.

Open the index.html and right-click anywhere on the webpage and select “Inspect” to open developer tools for Dom Manipulation. I like Google Chrome developer tools and go the second tab i.e. “Console”. now we will use createElement()‎ the function to create the new DOM element “P” stands for  “paragraph”

> const paragraph = document . createElement ( ‘p’ );
Element P has been created, now to verify execute the following command in the console terminal.

> console . log ( paragraph )

And the output will be:

<p> </ p>

As you see there is nothing between the p tags, means there is no text in it, because we did not add any text in it. Now we are going to add some text in the paragraph by executing the following command in the console terminal.

> paragraph.textContent = "I'm a new paragraph." ; 
> console.log ( paragraph ) 

The output will then be:

<p> I'm a new paragraph. </ p>

Using createElement()and textContent together will build a complete component node element. But we can use another child element to modify the content of the DOM element i.e innerHTML

> paragraph.innerHTML = "I'm a paragraph with <strong> bold </strong> text.";

NOTE:innerHTMLis a common method which is used to add content in the item, but the site will be at risk of cross-site scripting (xxs) attacks by adding a JavaScript instruction line that may harm to the site by using spam, so it is recommended to usetextContentHTML tags immediately. It is also possible to use the child element to add a text node.

> const text = document.createTextNode ( "I'm a new text node." ); 
> console.log( text ) 

The output will be as follows:

"I'm a new text node."

We have learned how to create new nodes and texts, but you have noticed, that these nodes are not visible in the front site. They will not be visible until we insert them into the document.

Add a text/data to the DOM

After constructing the elements and texts now we need to add them into the document by using a set of dependencies such as appendChild()‎and insertBefore()‎ to add items at the end, beginning or center of the parent element and the child can be used replaceChild(‎)to replace an old node with a new one.

Property / childDescription
node.appendChild()‎Add node as the last child of the parent element
node.insertBefore()‎Add a node at the same level as the parent node before the specified sibling node
node.replaceChild()‎Replace the status node with a new one

Now we have to practice the above-mentioned function for Dom Manipulation so we need a dummy task. Let’s create the following tasks using HTML.

  • Coffee
  • Tea
  • Milk
Add the following code

<!DOCTYPE html><html><body>
<h4>An Unordered List:</h4>
<ul><li>Coffee</li><li>Tea</li><li>Milk</li></ul>
</body></html>

and our Index.html will look like this.

Append Child

Now we’ll start practice and add up a new item “water” at the end of the list, and to do that we will have to create a dom element and add text to it.

> const preList= document . querySelector ( 'ul' ); 
> const newList= document . createElement ( 'li' );
> newList.textContent = 'Water' ; 
 Now we will add this new item at the end of the list using the child appendChild()‎: > newList.appendChild (newList);

When we open the editor of HTML which is in our case is “NotePad” and you will see that new item has been added in the li list at the end.

When you open the HTML file for the list, we’ll notice that a linew item has been added at the end ul:

<li>Coffee</li><li>Tea</li><li>Milk</li><li>Water</li>

Now we will practice inserting the new item at the top of the list. For this once again we have to create a list with createElement(). Let’s have a look

> const anotherList= document. createElement ( 'li' ); 
> anotherList. textContent = 'Soup' ; 

OK, now the list has been created now we have to insert this at the top of the list, for that we will use insertBefore()‎ function and pass some arguments. It has two arguments first new Node name, second is the name of the node where we have to insert. See the below-mentioned command syntax.

parentNode.insertBefore(newNode,nextSibling);

Repeat the previous instructions to our list, we will add the node that we previously built and named anotherListbefore the first element of the list, which is the item “Coffee”:

>newList.insertBefore(anotherList,newList.firstElementChild);

Now the file format Index.html will be:

<li>Soup</li><li>Coffee</li><li>Tea</li><li>Milk</li><li>Water</li>

If the new node is successfully added to the start of the list, and so we have learned how to add a node to a parent node, but we can also replace this node with a new node.

To edit an existing node in the task list, we’ll first create a new one:

> const modifiedList= document.createElement ( 'li' ); > modifiedList.textContent = 'Drink the tea' ; 

Replace Element

Now we will replace using the child list- replaceChild()‎ exactly the same like before we use the function insertBefore()‎where the first two variables are passed as arguments. The general syntax of this operation is:

parentNode.replaceChild (newNode ,oldNode );

Now we will replace the 3rd item in the list with the new item:

> todoList . ReplaceChild ( modifiedList, newList.Children [3]); 

The HTML file index.html will automatically be modified to look like this:

<li>Soup</li><li>Coffee</li><li>Drink the tea<li><li>Milk</li><li>Water</li>

Delete a text/item from the DOM

We have learned how to add the item in the DOM, replace the existing item with the new one. Now we will see how to delete the existing item from the DOM. We can delete the child note by using the remove() function.

FunctionDescription
node.removeChild()‎Delete the child node
node.remove()Delete the node itself

By using the list which we previously used, we’ll delete any item. Let’s delete the water from the list. Which is the at the end of the document For this operation we will use  removeChild() function as pass some arguments.

> todoList . removeChild ( todoList . lastElementChild );

The HTML file index.html will automatically be modified to look like this:

<li>Soup</li><li>Coffee</li><li>Drink the tea<li><li>Milk</li>

Now we will use the other child remove()‎who is deleting the same node directly:

> newList.children [1] .remove ();

The HTML file index.html will automatically be modified to look like this:

<li>Soup</li><li>Coffee</li><li>Drink the tea<li><li>Milk</li>

Using the functionsremoveChild()‎and remove()‎, we can remove any node of the DOM as we can use the property innerHTMLto remove the node child from the parent element by replacing an empty child text string (empty string) in the form "", but this method is not preferable in use.

Summary

In this article, we have learned Dom Manipulation using javaScript in the dom.how to add elements, how to add list and use to modify the existing element. We also learned how to delete the specific node from the Dom.

Thus, we have learned how to access DOM elements by using developers elements in Console.

Some References.

https://www.w3schools.com/tags/tag_ul.asp