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.

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 *