Page Content

Posts

How to Create New DOM Elements Using JavaScript

New DOM Elements

Elements, which comprise a tag and attributes, make up HTML code. An HTML page is represented by the DOM as a tree of objects, with HTML tags serving as element nodes and text inside tags as text nodes. These DOM elements can be chosen and altered using JavaScript. Using JavaScript to interact with a web page dynamically requires that you connect your knowledge to the DOM. Finding elements, modifying their qualities and values, adding style, and producing new elements are all part of this process.

Adding Attributes to New Elements

You can use the setAttribute() method to add or change attributes of the newly generated element node. Both elements that are already on the page and those you have just made but haven’t yet put can use this. An picture may have a border or alt text, or a new paragraph could get a class. Separate statements can be used to add more than one attribute.

Adding New Elements to the DOM

The next important step after generating and configuring an element is to add it to the current DOM tree so that it may be seen on the page. The element needs to be introduced to the DOM as a child of another element that already exists, like the <body> or a particular <div>.

The DOM can be expanded using a variety of techniques:

parentElement.appendChild(newElement): The method parentElement.appendChild(newElement) is often used. It adds the newElement as the parentElement’s final child. Any object that is a DOM element can use this function.

parentElement.insertBefore(newElement, referenceNode): Using parentElement.insertBefore(newElement, referenceNode) enables more accurate placement. The newElement is inserted into the parentElement just before the designated referenceNode.

element.append(…) and element.prepend(…): The methods element.append(…) and element.prepend(…), which are immediately accessible on Element objects, enable the prepending or adding of child nodes or even strings.

element.insertAdjacentHTML(position, text): This function converts a string to HTML and adds the nodes that result to the tree in relation to the element that the method is called on. These positions are “beforebegin,” “afterbegin,” “beforeend,” and “afterend.”

For inserting an element node, use insertAdjacentElement(); for inserting a text node, use insertAdjacentText().

<!DOCTYPE html>
<html>
<head>
<title>DOM Manipulation Examples</title>
</head>
<body>

<h1>Creating and Inserting Elements</h1>

<div id=”container”>
<p id=”existing-paragraph”>This is an existing paragraph.</p>
</div>

<script>
// This script is placed at the end of the body,
// ensuring the elements above are available when the script runs.

// — Example 1: Creating and Appending —

// 1. Create a new element (a div)
const newDiv = document.createElement(“div”); // Creates a new <div> element

// 2. Add some content to the new element
newDiv.textContent = “This div was created and appended using JavaScript.”; // Sets the text content
// Alternatively, you could use innerHTML for HTML content
// newDiv.innerHTML = “This div has <strong>bold</strong> text.”;

// 3. Get a reference to the body element
const body = document.body; // Reference to the <body> element

// 4. Append the new div to the body
body.appendChild(newDiv); // Adds newDiv as the last child of the body


// — Example 2: Creating and Inserting Before —

// 1. Create another new element (a paragraph)
const newParagraph = document.createElement(“p”); // Creates a new <p> element

// 2. Add content to the new element
newParagraph.textContent = “This paragraph was created and inserted before.”; // Sets the text content

// 3. Get a reference to an existing element (the paragraph with id=”existing-paragraph”)
const existingParagraph = document.getElementById(“existing-paragraph”); // Selects an element by its ID

// 4. Get a reference to the parent element of the existing paragraph (the div with id=”container”)
// We can get the parent using the parentNode property
const container = existingParagraph.parentNode;

// 5. Insert the new paragraph before the existing paragraph
container.insertBefore(newParagraph, existingParagraph); // Inserts newParagraph before existingParagraph within the container

</script>

</body>
</html>

Moreover, document.write() it has the ability to produce material, this is typically used to create the content of a document or new windows or frames. If it is called after the page has loaded, it may overwrite content that already exists in the document. Generally speaking, node based or insertAdjacent* approaches are better for dynamically adding elements to an already complicated DOM structure.

Important Consideration:

The function must execute after the components it interacts with have been generated in the document if it uses JavaScript to modify the DOM, including adding and removing elements. Either putting <script> tags right before the closing </body> tag or utilising event listeners, such as window.onload, to pause execution until the full page content loads are two ways to accomplish this.

You may create rich and engaging user experiences by using these strategies, which allow you to dynamically develop and adjust the structure of your web pages.

Index