Javascript 获取直接第一个子元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10474676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get immediate first child element
提问by mythofechelon
I'm writing a Chrome content script extension and I need to be able to target a specific element that, unfortunately, has no unique identifiers except its parent element.
我正在编写一个 Chrome 内容脚本扩展程序,我需要能够定位一个特定元素,不幸的是,除了其父元素之外没有唯一标识符。
I need to target the immediate first child element of parentElement
. console.log(parentElement)
reports both of the child elements/nodes perfectly, but the succeeding console logs (the ones that target the childNodes) always return an undefined
value no matter what I do.
我需要定位parentElement
. console.log(parentElement)
完美地报告了两个子元素/节点,但是undefined
无论我做什么,后续的控制台日志(针对 childNode 的那些)总是返回一个值。
This is my code so far
(I have excluded the actual names to avoid confusion and extra, unnecessary explanation)
到目前为止,这是我的代码
(我已经排除了实际名称以避免混淆和额外的不必要的解释)
function injectCode() {
var parentElement = document.getElementsByClassName("uniqueClassName");
if (parentElement && parentElement.innerHTML != "") {
console.log(parentElement);
console.log(parentElement.firstElementChild);
console.log(parentElement.firstChild);
console.log(parentElement.childNodes);
console.log(parentElement.childNodes[0]);
console.log(parentElement.childNodes[1]);
} else {
setTimeout(injectCode, 250);
}
}
How do I select the first child element/node of parentElement
?
如何选择 的第一个子元素/节点parentElement
?
Update:parentElement.children[0]
also has the same error as parentElement.childNodes[0]
.
更新:parentElement.children[0]
也有同样的错误parentElement.childNodes[0]
。
回答by Paul
Both these will give you the first child node:
这两个都会给你第一个子节点:
console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);
If you need the first child that is an element node then use:
如果您需要作为元素节点的第一个子节点,请使用:
console.log(parentElement.children[0]);
Edit
编辑
Ah, I see your problem now; parentElement
is an array.
啊,我现在明白你的问题了;parentElement
是一个数组。
If you know that getElementsByClassNamewill only return one result, which it seems you do, you should use [0]
to dearray (yes, I made that word up) the element:
如果您知道getElementsByClassName只会返回一个结果,这似乎是您所做的,那么您应该使用[0]
来对元素进行整理(是的,我编造了这个词):
var parentElement = document.getElementsByClassName("uniqueClassName")[0];