Categories
JavaScript Answers

How to get parent element and write holder div for siblings with JavaScript?

Spread the love

Sometimes, we want to get parent element and write holder div for siblings with JavaScript.

In this article, we’ll look at how to get parent element and write holder div for siblings with JavaScript.

How to get parent element and write holder div for siblings with JavaScript?

To get parent element and write holder div for siblings with JavaScript, we can use the parentNode property to get the parent node.

For instance, we write:

<div>
  <div id='child1'>
    hello world
  </div>
</div>

to add nested divs.

Then we write:

const child1 = document.getElementById("child1")
const parent = child1.parentNode
const contents = parent.innerHTML;
parent.innerHTML = `<div id="holder">${contents}</div>`;

to get the div with ID child1 with getElementById.

Then we get its parent node with parentNode.

Next, we get the parent node’s content with innerHTML.

And then we set parent.innerHTML to a string with a div wrapped around the contents.

Now the div with ID holder is wrapped around the div with ID child1.

Conclusion

To get parent element and write holder div for siblings with JavaScript, we can use the parentNode property to get the parent node.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *