How to rewrite html element from javascript?

I have an HTML page with some HTML element from ID="logo". I need to create a JS script (without external libs calls) that will overwrite this html element with another HTML element, for example "<div id=logo> stuff inside </div>".

+3
source share
3 answers

In most cases, this is just the content you want to replace, not the element itself. If you really replace the element, you will find that the event handlers associated with it are no longer bound (because they were attached to the old one).

Content Replacement

Replacing the contents of an element is simple:

var element;
element = document.getElementById("logo");
if (element) {
    element.innerHTML = "-new content-";
}

innerHTML , (, ). (. innerHTML .)

iself

, :

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 harmless because we're about to fix that).
    parent.insertBefore(newElement, element);

    // Remove the original
    parent.removeChild(element);
}

innerHTML DOM

, innerHTML, . , jQuery, Prototype .., , .

DOM, innerHTML ( , div /, ). , , , createElement, appendChild .., , innerHTML . HTML - , , . DOM, , . , , innerHTML - .

+14
0

Do you really need to "replace" an element or can you just switch its visibility? This is a method that is much simpler and more efficient. Most importantly, the content (html) is separate from the behavior (javascript).

function toggle() {
    document.getElementById("logo").style.display="none";
    document.getElementById("element_to_show").style.display="block";
}

see TJ answer if you really want to replace the item.

0
source

Source: https://habr.com/ru/post/1737912/


All Articles