Created
August 31, 2012 05:47
-
-
Save sofish/3549460 to your computer and use it in GitHub Desktop.
面试的时候我会经常问,js 中如何获得 <ul> 下的第一个 <li>,你的答案是什么?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 大家写在评论中吧,代码高亮可以这样写: | |
// ```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]; | |
} |
zieglar
commented
Aug 31, 2012
$("#ulid > li:first")
// ul 记为 <ul> 对象
ul.firstChild
ul.childNodes[0]
ul.children[0]
ul.getElementsByTagName('li')[0]
ul.querySelector('li')
如果只是单纯从 ul > li 这样的结构来说,ul.querySelectorAll(li)[0] || ul.getElementsByTagName('li')[0] 的方式也不错。
document.getElementById('ul-id').children[0]
var ul = document.getElementById('ul');
var li = ul.firstChild;
console.log(li.nodeName);
console.log(li.innerHTML);
document.getElementById("ui-ul").getElementsByTagName("li")[0];
former这个当遇到
<ul>text<!-- comment --> <li></li>...</ul>
这种情况的时候返回值就不正确了.
jq党
$("ul").find("li").first();
$("ul").find("li").eq(0);
@risent 哈哈,果然,还是需要一个循环
@qq286735628 @nomospace 加到上面了
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;
}
来晚了= =,有一样的了
用正则怎么样:
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