Skip to content

Instantly share code, notes, and snippets.

@renhao
Forked from sofish/first.js
Created December 14, 2012 01:27
Show Gist options
  • Save renhao/4281744 to your computer and use it in GitHub Desktop.
Save renhao/4281744 to your computer and use it in GitHub Desktop.
如何获得 <ul> 下的第一个 <li> ? - by sofish
// 加个性能测试:http://jsperf.com/get-dom-s-first-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;
}
// update: add 2 more
/* directly select
*cc @qq286735628
*/
util.first = function(element, tag) {
if(!element) return;
tag = tag || '*';
return element.querySelector ? element.querySelector(tag) : element.getElementsByTagName(tag)[0];
}
/* children selector
* cc @nomospace @qq286735628
*/
util.first = function(element) {
return element && element.children[0];
}
@renhao
Copy link
Author

renhao commented Dec 14, 2012

Element.firstChild
返回当前节点在DOM树中的第一个子节点, 如果没有子节点,则返回 null.
ie6-ie8支持此方法.

Element.firstElementChild
返回当前元素的第一个子元素节点,如果没有子元素节点,则返回null.该属性是只读的.
FF3.5 \ ie9-10 \ 现代浏览器支持

Element.children
children属性返回当前元素的子元素集合.
support all

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment