Wrapping an element in Vanilla JavaScript

Share on Facebook0Share on Reddit0Tweet about this on TwitterShare on Google+0

This is more of a snippet for my own memory — but here is a function to wrap an element (or set of elements with any arbitrary text. jQuery’s solution works well, but there’s no need to include such a heavy library for this small requirement.

Additionally, there are many (many) solutions on StackOverflow — but all take special care to work in old browsers. This is a optimized for new browser support and speed:

 

See the Pen PwwmEb by Michael Jasper (@mdjasper) on CodePen.

Share on Facebook0Share on Reddit0Tweet about this on TwitterShare on Google+0
  • Cory Brown

    Cool. I’m curious what the use case for this was. Did you consider [].forEach rather than a for loop? If so, what was compelling about the for loop?

    • mdjasper

      The use case was in doing a quick’n dirty retrofit of an old site, and needing to wrap some page content in containers to add full-bleed backgrounds. Couldn’t modify the server-side code, so had to hack it.

      I didn’t try array.forEach due to the document.querySelectorAll returning a NodeList (as opposed to an array), and doesn’t support that natively — without converting in into an array, or adding the forEach to the NodeList prototype. Didn’t test it with forEach though. Is there some magic there I’m missing out on?

      • Cory Brown

        [].slice.call(nodeList).forEach

        So no, no special magic. You’re still converting the nodeList to and array, but it works. I use it a lot.

        Also, in the use case you describe, it might be cool to take just two selectors as arguments. One, the selector that matches the wrapees and the other a selector that is expanded to a new node. That probably makes things much more complicated for your requirements though. I went down a similar path when doing fitIt.js but it was ultimately a dead end for me.