Home > Software design >  replace nested html elements with javascript
replace nested html elements with javascript

Time:04-11

I hava a huge dom element which i should replace some nested list html element in it. I also tried to remove the old nested element and add the new nested element but this also wasnt success.

const someNewNestedListElement = someNestedListElement
const replacedElement= elementToBeReplaced.replaceChild(someNewNestedListElement , elementToBeReplaced.querySelector(".someOldNestedListElement");

The dummy code above runs into an error. Can someone help me out here? Im pretty new to javascript and dom manipulation so i maybe need some tricks here.

CodePudding user response:

Try out this

const h2 = document.querySelector("h2"),
      button= document.querySelector("button"),
      newItem = document.createElement('p');

newItem.innerText = "replaced text";

button.onclick = function() {
try {
  h2.parentNode.replaceChild(newItem, h2);
  }
catch {
  console.log("already replaced");
  }
}
<div >
  
  <h1>Header1</h1>
  <div >
    <h2>Header2</h2>
  </div>
  <p>some dummy text</p>
  
  <button>replace header2</button>
</div>

  • Related