public
Created

Detect previousElementSibling/nextElementSibling

  • Download Gist
description.md
Markdown

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.

prevnextElementSibling.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
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);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.