Skip to content

Instantly share code, notes, and snippets.

@sofish
Created August 31, 2012 05:47
Show Gist options
  • Save sofish/3549460 to your computer and use it in GitHub Desktop.
Save sofish/3549460 to your computer and use it in GitHub Desktop.
面试的时候我会经常问,js 中如何获得 <ul> 下的第一个 <li>,你的答案是什么?
// 大家写在评论中吧,代码高亮可以这样写:
// ```js
// your code
// ```
// update: Fri Aug 31 08:39:21
// copyright: https://gist.github.com/3549352
// 加个性能测试: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];
}
@Pentium286
Copy link

var ul = document.getElementById('ul');
var li = ul.firstChild;
console.log(li.nodeName);
console.log(li.innerHTML);

@vikingmute
Copy link

 document.getElementById("ui-ul").getElementsByTagName("li")[0];

@risent
Copy link

risent commented Aug 31, 2012

former这个当遇到

<ul>text<!-- comment --> <li></li>...</ul>

这种情况的时候返回值就不正确了.

@ciaoca
Copy link

ciaoca commented Aug 31, 2012

jq党
$("ul").find("li").first();
$("ul").find("li").eq(0);

@sofish
Copy link
Author

sofish commented Aug 31, 2012

@risent 哈哈,果然,还是需要一个循环

@sofish
Copy link
Author

sofish commented Aug 31, 2012

@qq286735628 @nomospace 加到上面了

@kiddkai
Copy link

kiddkai commented Aug 31, 2012

util = {};

util.first = function(elem) {
   if (!elem && !elem.firstChild) return null;
   var first_child = elem.firstChild;
   while(!(first_child.nodeType == 1) && first_child.nextSibling)
     first_child = first_child.nextSibling;
   return first_child.nodeType == 1 ? first_child : null;
}

来晚了= =,有一样的了

@ghyghoo8
Copy link

ghyghoo8 commented Sep 3, 2012

用正则怎么样:

util.first=function(elem,tag){
var html=elem.innerHTML,reg=new Reg('<'+tag+'>.*?</'+tag+'>','ig');
var arr=reg.exec(html);
return arr.pop();
}

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