如何獲得指定節(jié)點的后面所有節(jié)點
var x=document.getElementsByTagName("li");
這里 x.length 是 6?
將 if 改為 while 后,應(yīng)該能夠獲取指定節(jié)點后的所有節(jié)點,但只能獲取 3 個,為啥呀?
? ? if (y!=null){
? ? ? ? document.write("<br />nextsibling: ");
? ? ? ? document.write(y.nodeName);
? ? ? ? document.write(" = ");
? ? ? ? document.write(y.innerHTML);
? ? ? ? y=get_nextSibling(y);? ??
完整代碼:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>nextSibling</title>
</head>
<body>
<ul id="u1">? ?
? ? ? ? ? ? <li id="a">javascript</li>? ?
? ? ? ? ? ? <li id="b">jquery</li>? ?
? ? ? ? ? ? <li id="c">html</li>? ?
? ? ? ? </ul>? ?
? ? ? ? <ul id="u2">? ?
? ? ? ? ? ? <li id="d">css3</li>? ?
? ? ? ? ? ? <li id="e">php</li>? ?
? ? ? ? ? ? <li id="f">java</li>? ?
? ? ? ? </ul>? ?
<script type="text/javascript">
? ? function get_nextSibling(n){
? ? ? ? var x=n.nextSibling;
? ? ? ? while (x && x.nodeType!=1){
? ? ? ? ? ? x=x.nextSibling;
? ? ? ? }
? ? ? ? return x;
? ? }
? ? var x=document.getElementsByTagName("li")[0];
? ? document.write(x.nodeName);
? ? document.write(" = ");
? ? document.write(x.innerHTML);
? ??
? ? var y=get_nextSibling(x);
? ??
? ? while(y!=null){
? ? ? ? document.write("<br />nextsibling: ");
? ? ? ? document.write(y.nodeName);
? ? ? ? document.write(" = ");
? ? ? ? document.write(y.innerHTML);
? ? ? ? y=get_nextSibling(y);
? ? }
? ? ? document.write("<br>已經(jīng)是最后一個節(jié)點");? ? ??
</script>
</body>
</html>
2022-11-03
第一步:var x=document.getElementsByTagName("li")[0];? 得到第一個li.
第二步:var y=get_nextSibling(x);調(diào)用函數(shù),
第三步:var x=n.nextSibling;? ? 此時節(jié)點變作文本節(jié)點,類型為3,進入while判斷
第四步:
while (x && x.nodeType!=1){
? ? ? ? ? ? x=x.nextSibling;
? ? ? ? }判斷后節(jié)點變作第二個li,類型為1.
第五步:返回第二個節(jié)點對象給y,進入while(y!=null)
第六步:與y此時是兄弟的節(jié)點只有 "空白文本","第三個li","空白文本"? ,一共三個兄弟節(jié)點,所以循環(huán)輸出三個節(jié)點。over
注意:nextSibling這是下一個兄弟節(jié)點的意思,不是下一個節(jié)點。
關(guān)于這個var x=document.getElementsByTagName("li");獲得是標簽為li的元素節(jié)點集合,和你問的第一個li的節(jié)點后續(xù)的兄弟節(jié)點是不同的,這里li集合里后面三個li和第一個li根本不是兄弟。