Wrap element snippet
levimcg.com·189w

I’ve found myself needing to do this on a couple of projects lately so it seemed like a good idea to write it down here as a snippet to reference later.

This sort of a vanilla replacement for jQuery’s .wrap() method

/**
* Helper function to wrap one element with a new element
*
* @param {String} wrapWith - the name the element to create as the wrapper
* @param {Element} toWrap - The existing element to wrap
* @param {Object} attributes - An object of key value pairs used to create HTML attributes
*/
function wrap(wrapWith, toWrap, attributes) {
const wrapperElement = document.createElement(wrapWith);
if (attributes) {
for (let attr in attributes) {
wrapperElement.setAttribute(attr, attributes[attr])
}
}
toWrap.parentNode.insertBefore(wrapperElemen...

Similar Posts

Loading similar posts...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help