Categories
JavaScript Answers

How to wrap content in a div with JavaScript?

Spread the love

Sometimes, we want to wrap content in a div with JavaScript.

In this article, we’ll look at how to wrap content in a div with JavaScript.

How to wrap content in a div with JavaScript?

To wrap content in a div with JavaScript, we can call the appendChild method.

For instance, we write

const wrap = (toWrap, wrapper) => {
  const newWrapper = wrapper ?? document.createElement("div");
  toWrap.parentNode.appendChild(newWrapper);
  return newWrapper.appendChild(toWrap);
};

to define the wrap function.

In it, we get the wrapperor create a new div withcreateElement` if it’s not set.

Then we call toWrap.parentNode.appendChild to append the newWrapper as the child of the parent node of the toWrap element.

And then we use newWrapper.appendChild(toWrap) to append toWrap as the last child of newWrapper.

Conclusion

To wrap content in a div with JavaScript, we can call the appendChild method.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.