Replace element with javascript

Replace a DOM Element

To replace a DOM element in the DOM tree, you follow these steps:

  • First, select the DOM element that you want to replace.
  • Then, create a new element.
  • Finally, select the parent element of the target element and replace the target element by the new element using the replaceChild() method.

See the following HTML document:

html> head> title>Replace a DOM element title> head> body> ul> li>a href="/home">Home a> li> li>a href="/service">Service a> li> li>a href="/about">About a> li> ul> script src="js/app.js"> script> body> html>Code language: HTML, XML (xml)

To select the last list item element, you follow the above steps:

First, select the last list item using the querySelector() method:

const listItem = document.querySelector("li:last-child");Code language: JavaScript (javascript)

Second, create a new list item element:

const newItem = document.createElement('li'); newItem.innerHTML = 'Products';Code language: JavaScript (javascript)

Finally, get the parent of the target element and call the replaceChild() method:

listItem.parentNode.replaceChild(newItem, listItem);Code language: CSS (css)

Источник

Читайте также:  404 Not Found

Element: replaceWith() method

The Element.replaceWith() method replaces this Element in the children list of its parent with a set of Node or string objects. String objects are inserted as equivalent Text nodes.

Syntax

replaceWith(param1) replaceWith(param1, param2) replaceWith(param1, param2, /* … ,*/ paramN) 

Parameters

A set of Node or string objects to replace.

Return value

Exceptions

Thrown when the node cannot be inserted at the specified point in the hierarchy.

Examples

Using replaceWith()

const div = document.createElement("div"); const p = document.createElement("p"); div.appendChild(p); const span = document.createElement("span"); p.replaceWith(span); console.log(div.outerHTML); // " " 

replaceWith() is unscopable

The replaceWith() method is not scoped into the with statement. See Symbol.unscopables for more information.

with (node)  replaceWith("foo"); > // ReferenceError: replaceWith is not defined 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

How to overwrite html element from javascript?

I have HTML page with some HTML element with ID=»logo» . I need to create JS script (with no external libs calls) that will overwrite that html element with other HTML element like «

» .

i’m sorry — ‘no external libs calls’ means ? you don’t want to reference code on another site? or have you ruled out using the obvious solution to this — jQuery- included and loaded from your own server?

3 Answers 3

Most of the time, it’s just the content you want to replace, not the element itself. If you actually replace the element, you’ll find that event handlers attached to it are no longer attached (because they were attached to the old one).

Replacing its content

Replacing the element’s content is easy:

var element; element = document.getElementById("logo"); if (element)

The innerHTML property has only recently been standardized, but is supported by all major browsers (probably most minor ones, too). (See notes below about innerHTML and alternatives.)

Replacing the element iself

Actually replacing the element itself is a little harder, but not much:

var element, newElement, parent; // Get the original element element = document.getElementById("logo"); // Assuming it exists. if (element) < // Get its parent parent = element.parentNode; // Create the new element newElement = document.createElement('div'); // Set its ID and content newElement.id = "logo"; newElement.innerHTML = "-new content here-"; // Insert the new one in front of the old one (this temporarily // creates an invalid DOM tree [two elements with the same ID], // but that's harmless because we're about to fix that). parent.insertBefore(newElement, element); // Remove the original parent.removeChild(element); >

Notes on innerHTML and other DOM manipulation techiques

There are a number of wrinkles around using innerHTML in certain browsers, mostly around tables and forms. If you can possibly use a library like jQuery, Prototype, etc., I’d do so, as they’ve got workarounds for those issues built-in.

Alternatively, you can use the various other DOM methods rather than innerHTML (the same ones I used for creating the div and adding/removing, above). Note that in most browsers, doing any significant amount of markup by doing a bunch of createElement , appendChild , etc., calls rather than using innerHTML will be dramatically slower. Parsing HTML into their internal structures and displaying it is fundamentally what browsers do, and so they’re highly optimized to do that. When you go through the DOM interface, you’re going through a layer built on top of their internal structures and not getting the advantage of their optimizations. Sometimes you have to do it that way, but mostly, innerHTML is your friend.

Источник

Замена DOM-элемента и его содержимого на чистом JS

А теперь представьте, что вы хотите полностью заменить элемент #greeting вот этим:

 

Hi, universe!

The sun is always shining!

Как бы вы это сделали? Рассмотрим 3 возможных подхода.

Метод Node.replaceChild()

Метод Node.replaceChild() вызывается на родительском контейнере элемента, который вы хотите заменить.

Метод принимает 2 аргумента: новый элемент и текущий. Он заменяет элемент, переданный вторым аргументом на элемент, переданный первым.

Используя этот подход, вы должны сначала создать новый элемент, используя метод document.createElement() . Затем нужно задать для него все необходимые свойства и добавить контент. После этого вы можете использовать метод Node.replaceChild() для внедрения нового элемента в DOM.

Метод Node.replaceChild() работает во всех современных браузерах, а также в IE9.

Метод Node.replaceWith()

Метод Node.replaceWith() более современный и призван немного облегчить процесс.

Он вызывается непосредственно на заменяемом элементе, принимая новый элемент в качестве единственного аргумента.

При этом подходе вы также должны сначала создать новый элемент, используя метод document.createElement() . Затем задать его свойства и добавить контент, после чего вызвать Node.replaceWith() для замены.

Метод Node.replaceWith() работает во всех современных браузерах, но не поддерживается IE.

Свойство Element.outerHTML

Свойство Element.outerHTML существует уже давно, но я лишь недавно начал его использовать.

Оно аналогично свойству Element.innerHTML , но в отличие от него также содержит и сам элемент. Вы можете использовать его как для получения HTML-кода элемента, так и для его установки.

Используя свойство Element.innerHTML исходного элемента вы можете просто заменить его требуемой HTML-строкой.

Свойство Element.outerHTML работает во всех современных браузерах, а также поддерживается IE4 и выше (да да, IE4. ).

Какой же подход использовать?

Лично я предпочитаю Element.outerHTML из-за его простоты и широкой поддержки браузерами.

Бывают ситуации, в которых использование других подходов более предпочтительно, но именно этот я использую в 99% случаев.

Источник

How to replace DOM Element JavaScript? [SOLVED]

Welcome to our comprehensive guide on «How to Replace DOM Elements in JavaScript»! In today’s fast-paced web development landscape, it’s vital to understand how to manipulate and interact with the Document Object Model (DOM) effectively. In this tutorial, we’ll explore the essential techniques for replacing DOM elements using JavaScript, ensuring that you have the skills necessary to build dynamic, interactive web applications. Get ready to dive into the world of DOM manipulation and unlock the full potential of your web projects!

Different methods to replace DOM Element with JavaScript

JavaScript is a client-side scripting language used to add interactivity to web pages. One of the main tasks in JavaScript is to manipulate the Document Object Model (DOM), which is a hierarchical tree structure of all the HTML elements on a web page.

One common DOM manipulation task is replacing elements in the DOM. In this article, we will discuss two methods for replacing elements in the DOM: the replaceChild() method and the replaceWith() method.

In this article, we will discuss how to replace elements in DOM using JavaScript built-in methods.

Method-1: Using the replaceChild() method to replace element

The replaceChild() method is used to replace a child node in a parent node. It takes two arguments: the new node to be added and the old node to be replaced.

Here is the syntax for the replaceChild() method to replace element in DOM.

parentNode.replaceChild(newNode, oldNode); 

Before we go into the example to illustrate how the replaceChild() method works, we need to understand that we will need the createElement() to create the new node or element we need to replace the element in the DOM.

The syntax to create the element in JavaScript using the createElement() can be seen below

document.createElement(element); 

Now, we can replace elements using the replaceChild() and createElement() method. To illustrate the process to replace an element or node, we will create a simple HTML page and replace the heading with a new heading text and add a class name to the new element created.

let oldNode = document.getElementById("old"); let newNode = document.createElement("h1"); newNode.className = "new-heading"; newNode.innerHTML = "DOM Manipulation and Element Replacement"; let parentNode = oldNode.parentNode; parentNode.replaceChild(newNode, oldNode); 

javascript replace element

In the code, we obtain the element we want to replace with the getElementById() method and create the element we want to add with the createElement() method. Afterwards, we assign a new class using the className property and add new content to the newly created element newNode . Then, we reference the new element/node to the old node and apply the replaceChild() method to replace the old node/element.

Method-2: Using the replaceWith() method to replace element

The replaceWith() method is a more modern and concise way to replace an element in the DOM. It is available in modern browsers and can be used as an alternative to replaceChild() . The method works pretty much like the replaceChild() method. It replaces the element in the children list of its parent with a set of Node or string objects.

Here is the syntax to use the replaceWith() method

oldNode.replaceWith(newNode); 

Similarly, we need to use the createElement() method to create the element we are going to add to replace the old element. Then, we use the replaceWith() method to replace the element. To illustrate this, we will replace the second list item — replaceWith() — within the HTML page in the previous section with a new text — Wow — replaceWith() is amazing .

Our script.js file would go thus;

let oldNode = document.querySelectorAll("li")[1]; let newNode = document.createElement("li"); newNode.className = "new-list"; newNode.innerHTML = "Wow - replaceWith() is amazing"; oldNode.replaceWith(newNode); 

javascript replace element

In the code, we use a different DOM selector method — querySelectorAll — to obtain all the li element, and since we know the order of the li element with the text we want to replace, we can select it with the bracket notation. Then, we apply a class name and innerHTML property and use the replaceWith() method.

Summary

In this article, we discussed two methods for replacing elements in the DOM: the replaceChild() method and the replaceWith() method. Both methods allow you to replace an element in the DOM, but the replaceWith() method is more modern and concise.

When replacing elements in the DOM, it’s important to understand the difference between the two methods and choose the one that best fits your needs. Whether you’re using the replaceChild() method or the replaceWith() method, being able to replace elements in the DOM is a powerful tool for adding interactivity to web pages and improving user experience.

Источник

Оцените статью