Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Detect previousElementSibling/nextElementSibling

Description

My team likes to use the previousElementSibling and nextElementSibling methods as it saves them having to filter out TEXT_NODES (which the majority of the time - when sifting through the DOM - they don't have to worry about).

Internet Explorer <= 8 doesn't support either method, but it's current DOM implementation ignores TEXT_NODES (when using previousSibling and nextSibling) so they already act like previousElementSibling and nextElementSibling.

But when checking over my teams code I noticed that they would use a conditional code branching in every instance where they wanted to use previousElementSibling and nextElementSibling, so to try and help keep their code DRY I just used a very basic feature detection script to abstract these methods into two separate functions for them to use instead.

Caveat

This feature detection assumes the head and a body tags are available at the time of the script executing.

var prevElementSibling = (function(){
var supported = !!document.body.previousElementSibling,
prev = (supported) ? 'previousElementSibling' : 'previousSibling';
return function(currentElement) {
return currentElement[prev];
};
}());
var nextElementSibling = (function(){
var supported = !!document.getElementsByTagName('head')[0].nextElementSibling,
next = (supported) ? 'nextElementSibling' : 'nextSibling';
return function(currentElement) {
return currentElement[next];
};
}());
var head = prevElementSibling(document.body);
console.log(head);
var body = nextElementSibling(document.getElementsByTagName('head')[0]);
console.log(body);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.