Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save brandonkramer/f4db22ba630c92517f658337bceb8e54 to your computer and use it in GitHub Desktop.
Save brandonkramer/f4db22ba630c92517f658337bceb8e54 to your computer and use it in GitHub Desktop.
Wrap elements and their previous and next siblings with vanilla javascript
// 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