Kamran İbrahimov
Kamran İbrahimov

Reputation: 59

How to replace an HTML element with another one?

For example, how can I replace this code of page:

<div class="parent">
    <!-- possibly other elements -->
    <div class="toselect">hello people</div>
    <!-- possibly other elements -->
</div>

with this one:

<div class="parent">
    <!-- possibly other elements -->
    <span class="new" style="color:red">hi guys</span>
    <!-- possibly other elements -->
</div>

? Note that number of .parent's children, full code of any element are not known. The only things known are a selector necessary to select the element to be replaced ('.toselect'), and the code of the element to be added.

Upvotes: 0

Views: 1554

Answers (2)

SequenceDigitale.com
SequenceDigitale.com

Reputation: 4094

simply use "outerHTML" instead of "innerHTML" on the object.

Upvotes: 0

Rohit Utekar
Rohit Utekar

Reputation: 848

Try using the below code.

document.getElementById("change").addEventListener("click", function() {
  var oldEle = document.querySelector(".toselect");
  var newEle = document.createElement("span");
  newEle.innerHTML = "hi guys";
  newEle.classList.add("new");
  newEle.style.color = "red";
  oldEle.parentNode.replaceChild(newEle, oldEle);
});
<div class="parent">
    <div>other element</div>
    <div class="toselect">hello people</div>
    <div>other element</div>
</div>
<br>
<button id="change">Change Element</button>

Upvotes: 1

Related Questions