Skip to content

Instantly share code, notes, and snippets.

@livingston
Created March 24, 2010 20:10
Show Gist options
  • Save livingston/342723 to your computer and use it in GitHub Desktop.
Save livingston/342723 to your computer and use it in GitHub Desktop.
DOM Helper Methods
/* Collection of DOM Helper Methods
* Livingston Samuel
*/
var DOM = {};
/* Get Next Element node Sibling - Equivalent of nextElementSibling */
DOM.next = function (elem) {
var sibling = elem.nextSibling;
while(sibling && sibling.nodeType !== 1) { //Loop as long as the nextSibling is not an Element node
sibling = sibling.nextSibling;
}
return sibling; //Returns null if there is no Element node sibling, else returns reference to the next Element node Sibling
};
//The above method is approx. 100 times faster than jQuery(elem).next()
/* Get All the Next Element node Siblings */
DOM.nextAll = function (elem, allNodes) {
var sibling = elem.nextSibling,
result = [];
if (allNodes) {
while (sibling) {
result.push(sibling);
sibling = sibling.nextSibling;
}
} else {
while (sibling) {
if (sibling.nodeType === 1) {
result.push(sibling);
}
sibling = sibling.nextSibling;
}
}
return result;
};
/* Get Previous Element node Sibling - Equivalent of previousElementSibling */
DOM.prev = function (elem) {
var sibling = elem.previousSibling;
while(sibling && sibling.nodeType !== 1) { //Loop as long as the previousSibling is not an Element node
sibling = sibling.previousSibling;
}
return sibling; //Returns null if there is no Element node sibling, else returns reference to the previous Element node Sibling
};
/* Get All the Previous Element node Siblings */
DOM.prevAll = function (elem, allNodes) {
var sibling = elem.previousSibling,
result = [];
if (allNodes) {
while (sibling) {
result.push(sibling);
sibling = sibling.previousSibling;
}
} else {
while (sibling) {
if (sibling.nodeType === 1) {
result.push(sibling);
}
sibling = sibling.previousSibling;
}
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment