Skip to content

Instantly share code, notes, and snippets.

@appelgran
Created February 23, 2022 11:12
Show Gist options
  • Save appelgran/ec8856228861fef577a7cd0d542bcae6 to your computer and use it in GitHub Desktop.
Save appelgran/ec8856228861fef577a7cd0d542bcae6 to your computer and use it in GitHub Desktop.
Vanilla javascript version of jquery siblings with selector (plus callback)
/*
Browser Compatibility:
IE: 9, Safari: 3.1, Chrome: 1, Edge: 12, Firefox: 3.5
*/
function getSiblings(el, sel) {
var matches = [];
var targets = sel ? el.parentNode.querySelectorAll(sel) : el.parentNode.children;
for (var target of targets) {
if (target !== el && target.parentNode === el.parentNode) {
matches.push(target);
}
}
return matches;
}
/*
Browser Compatibility:
IE: -, Safari: 7, Chrome: 27, Edge: 79, Firefox: 32
*/
function getSiblings(el, sel) {
var matches = [];
var targets = sel ? el.parentNode.querySelectorAll(":scope > " + sel) : el.parentNode.children;
for (var target of targets) {
if (target !== el) {
matches.push(target);
}
}
return matches;
}
/*
Browser Compatibility:
IE: 9, Safari: 3.1, Chrome: 1, Edge: 12, Firefox: 3.5
*/
function siblings(el, sel, cb) {
var matches = [];
var targets = sel ? el.parentNode.querySelectorAll(sel) : el.parentNode.children;
for (var target of targets) {
if (target !== el && target.parentNode === el.parentNode) {
matches.push(target);
}
}
if (cb) {
matches.forEach(cb);
}
return matches;
}
/*
Browser Compatibility:
IE: -, Safari: 7, Chrome: 27, Edge: 79, Firefox: 32
*/
function siblings(el, sel, cb) {
var matches = [];
var targets = sel ? el.parentNode.querySelectorAll(":scope > " + sel) : el.parentNode.children;
for (var target of targets) {
if (target !== el) {
matches.push(target);
}
}
if (cb) {
matches.forEach(cb);
}
return matches;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment