Skip to content

Instantly share code, notes, and snippets.

@sofish
Created August 31, 2012 05:30
Show Gist options
  • Save sofish/3549352 to your computer and use it in GitHub Desktop.
Save sofish/3549352 to your computer and use it in GitHub Desktop.
DOM: get the first child of a DOM element
var util = {};
/* now: we use this one */
util.first = function(element) {
if(!element) return;
return element[element.firstElementChild ? 'firstElementChild' : 'firstChild'];
}
/* former: */
util.first = function(element) {
if(!element) return;
var first= element.firstChild;
while(first && first.nodeType !==1) first = first.nextSibling;
return first;
}
/* directly select */
util.first = function(element, tag) {
if(!element) return;
tag = tag || '*';
return element.querySelector ? element.querySelector(tag) : element.getElementsByTagName(tag)[0];
}
/* children selector */
util.first = function(element) {
return element && element.children[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment