Last active
April 12, 2022 23:57
-
-
Save brandonkramer/f4db22ba630c92517f658337bceb8e54 to your computer and use it in GitHub Desktop.
Wrap elements and their previous and next siblings with vanilla javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Get all the elements | |
document.querySelectorAll( '.my-element' ).forEach( (el) => { | |
var prevEl = el.previousElementSibling, nextEl = el.nextElementSibling, elArr = [], html = ''; | |
if ( prevEl === null || nextEl === null ) return; | |
// In case you want to include the two elements before the previous sibling | |
[prevEl.previousElementSibling, prevEl.previousElementSibling.previousElementSibling].forEach((topEl) => { | |
if ( topEl !== null ) elArr.push(topEl); | |
}) | |
elArr.push(prevEl, el, nextEl); | |
elArr.forEach( (elHTML) => html += elHTML.outerHTML ); | |
prevEl.insertAdjacentHTML( 'beforebegin','<div class="my-wrapper">' + html + '</div>' ); | |
elArr.forEach( (origin) => origin.remove() ); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment