查看所有這些屬性如果你只需要從父元素的直接孩子,看看下面的例子:
<div id="div1">
Parent
<div id="div2">
Child
<div id="div3-1">
N-child 1
</div>
<div id="div3-2">
N-child 2
</div>
</div>
</div>
<input type="button" id="btn-action" value="Run" />
<div id="result"></div>
JavaScript:
document.getElementById("btn-action").addEventListener("click",function(e) {
var div1 = document.getElementById("div1"),
div2 = document.getElementById("div2"),
nchild1 = document.getElementById("div3-1"),
nchild2 = document.getElementById("div3-2");
document.getElementById("result").innerHTML =
"<br/>div2 is child of div1? - " + fnIsChild(div1, div2) +
"<br/>div3-1 is child of div1? - " + fnIsChild(div1, nchild1) +
"<br/>div3-2 is child of div1? - " + fnIsChild(div1, nchild1);
});
function fnIsChild(parentElem, childElem) {
var childNodes = parentElem.childNodes,
max = childNodes.length,
n;
for(n = 0; n < max; n += 1) {
if(childNodes[n] === childElem) return true;
}
return false;
}
exactl Ÿ我在找什麼:),不會讓我把這個標記爲應答10分鐘,儘管...... – 2013-04-07 20:01:19
@at .:很高興幫助。 – 2013-04-07 20:01:37