GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • JS Array Object
  • JS Boolean Object
  • JS Date Object
  • JS Math Object
  • JS Number Object
  • JS String Object
  • JS Reserved Keywords
  • More references

This view

  • Original page
  • New address

GeezerVison is showing www.tutorialrepublic.com — JavaScript Manipulating Elements - Tutorial Republic

TutorialRepublic
HOME HTML5 CSS3 JAVASCRIPT JQUERY BOOTSTRAP5 v4.6 PHP7 SQL REFERENCES EXAMPLES FAQ SNIPPETS Online HTML Editor
JAVASCRIPT BASIC
JS Introduction JS Getting Started JS Syntax JS Variables JS Generating Output JS Data Types JS Operators JS Events JS Strings JS Numbers JS If…Else JS Switch…Case JS Arrays JS Sorting Arrays JS Loops JS Functions JS Objects
JAVASCRIPT & DOM
JS DOM Nodes JS DOM Selectors JS DOM Styling JS DOM Get Set Attributes JS DOM Manipulation JS DOM Navigation
JAVASCRIPT & BOM
JS Window JS Screen JS Location JS History JS Navigator JS Dialog Boxes JS Timers
JAVASCRIPT ADVANCED
JS Date and Time JS Math Operations JS Type Conversions JS Event Listeners JS Event Propagation JS Borrowing Methods JS Hoisting Behavior JS Closures JS Strict Mode JS JSON Parsing JS Error Handling JS Regular Expressions JS Form Validation JS Cookies JS AJAX Requests JS ES6 Features
JAVASCRIPT EXAMPLES
JS Practice Examples JS FAQ's Answers
JAVASCRIPT REFERENCE
  • JS Properties and Methods
    • JS Array Object
    • JS Boolean Object
    • JS Date Object
    • JS Math Object
    • JS Number Object
    • JS String Object
  • JS Reserved Keywords
  • More references
Advertisements

JavaScript DOM Manipulation

In this tutorial you will learn how to manipulate elements in JavaScript.

Manipulating DOM Elements in JavaScript

Now that you've learnt how to select and style HTML DOM elements. In this chapter we will learn how to add or remove DOM elements dynamically, get their contents, and so on.

Adding New Elements to DOM

You can explicitly create new element in an HTML document, using the document.createElement() method. This method creates a new element, but it doesn't add it to the DOM; you'll have to do that in a separate step, as shown in the following example:

Example

Try this code »
<div id="main">
    <h1 id="title">Hello World!</h1>
    <p id="hint">This is a simple paragraph.</p>
</div>
 
<script>
// Creating a new div element 
let newDiv = document.createElement("div");
 
// Creating a text node 
let newContent = document.createTextNode("Hi, how are you doing?");
 
// Adding the text node to the newly created div
newDiv.appendChild(newContent);
 
// Adding the newly created element and its content into the DOM 
let currentDiv = document.getElementById("main"); 
document.body.appendChild(newDiv, currentDiv);
</script>

The appendChild() method adds the new element at the end of any other children of a specified parent node. However, if you want to add the new element at the beginning of any other children you can use the insertBefore() method, as shown in example below:

Example

Try this code »
<div id="main">
    <h1 id="title">Hello World!</h1>
    <p id="hint">This is a simple paragraph.</p>
</div>
 
<script>
// Creating a new div element 
let newDiv = document.createElement("div");
 
// Creating a text node 
let newContent = document.createTextNode("Hi, how are you doing?");
 
// Adding the text node to the newly created div
newDiv.appendChild(newContent);
 
// Adding the newly created element and its content into the DOM 
let currentDiv = document.getElementById("main"); 
document.body.insertBefore(newDiv, currentDiv);
</script>

Getting or Setting HTML Contents to DOM

You can also get or set the contents of the HTML elements easily with the innerHTML property. This property sets or gets the HTML markup contained within the element i.e. content between its opening and closing tags. Checkout the following example to see how it works:

Example

Try this code »
<div id="main">
    <h1 id="title">Hello World!</h1>
    <p id="hint">This is a simple paragraph.</p>
</div>
 
<script>
// Getting inner HTML conents
let contents = document.getElementById("main").innerHTML;
alert(contents); // Outputs inner html contents
 
// Setting inner HTML contents
let mainDiv = document.getElementById("main");
mainDiv.innerHTML = "<p>This is <em>newly inserted</em> paragraph.</p>";
</script>

As you can see how easily you can insert new elements into DOM using the innerHTML property, but there is one problem, the innerHTML property replaces all existing content of an element. So if you want to insert the HTML into the document without replacing the existing contents of an element, you can use the insertAdjacentHTML() method.

This method accepts two parameters: the position in which to insert and the HTML text to insert. The position must be one of the following values: "beforebegin", "afterbegin", "beforeend", and "afterend". This method is supported in all major browsers.

The following example shows the visualization of position names and how it works.

Example

Try this code »
<!-- beforebegin -->
<div id="main">
    <!-- afterbegin -->
    <h1 id="title">Hello World!</h1>
    <!-- beforeend -->
</div>
<!-- afterend -->
 
<script>
// Selecting target element
let mainDiv = document.getElementById("main");
 
// Inserting HTML just before the element itself, as a previous sibling
mainDiv.insertAdjacentHTML('beforebegin', '<p>This is paragraph one.</p>');
 
// Inserting HTML just inside the element, before its first child
mainDiv.insertAdjacentHTML('afterbegin', '<p>This is paragraph two.</p>');
 
// Inserting HTML just inside the element, after its last child
mainDiv.insertAdjacentHTML('beforeend', '<p>This is paragraph three.</p>');
 
// Inserting HTML just after the element itself, as a next sibling
mainDiv.insertAdjacentHTML('afterend', '<p>This is paragraph four.</p>');
</script>

Note: The beforebegin and afterend positions work only if the node is in the DOM tree and has a parent element. Also, when inserting HTML into a page, be careful not to use user input that hasn't been escaped, to prevent XSS attacks.


Removing Existing Elements from DOM

Similarly, you can use the removeChild() method to remove a child node from the DOM. This method also returns the removed node. Here's an example:

Example

Try this code »
<div id="main">
    <h1 id="title">Hello World!</h1>
    <p id="hint">This is a simple paragraph.</p>
</div>

<script>
let parentElem = document.getElementById("main");
let childElem = document.getElementById("hint");
parentElem.removeChild(childElem);
</script>

It is also possible to remove the child element without exactly knowing the parent element. Simply find the child element and use the parentNode property to find its parent element. This property returns the parent of the specified node in the DOM tree. Here's an example:

Example

Try this code »
<div id="main">
    <h1 id="title">Hello World!</h1>
    <p id="hint">This is a simple paragraph.</p>
</div>
 
<script>
let childElem = document.getElementById("hint");
childElem.parentNode.removeChild(childElem);
</script>

Replacing Existing Elements in DOM

You can also replace an element in HTML DOM with another using the replaceChild() method. This method accepts two parameters: the node to insert and the node to be replaced. It has the syntax like parentNode.replaceChild(newChild, oldChild);. Here's an example:

Example

Try this code »
<div id="main">
    <h1 id="title">Hello World!</h1>
    <p id="hint">This is a simple paragraph.</p>
</div>
 
<script>
let parentElem = document.getElementById("main");
let oldPara = document.getElementById("hint");
 
// Creating new elememt
let newPara = document.createElement("p");
let newContent = document.createTextNode("This is a new paragraph.");
newPara.appendChild(newContent);
 
// Replacing old paragraph with newly created paragraph
parentElem.replaceChild(newPara, oldPara);
</script>
Previous Page Next Page
Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties
Advertisements

Is this website helpful to you? Please give us a like, or share your feedback to help us improve. Connect with us on Facebook and Twitter for the latest updates.

About Us

Our Story Terms of Use Privacy Policy

Contact

Contact Us Report Error Guest Posts Advertise

Interactive Tools

Bootstrap Icon Search Utility HTML Formatter Title & Meta Length Calculator HTML Color Picker Bootstrap Button Generator SQL Playground Font Awesome Icon Finder HTML Editor

TutorialRepublic

BMC
Copyright © 2026 Tutorial Republic. All Rights Reserved.
Share This:
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.