« Back to Index

Detect previousElementSibling/nextElementSibling

View original Gist on GitHub

Tags: #js

description.md

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

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);