简体   繁体   English

立即获得第一个子元素

[英]Get immediate first child element

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 . 我需要定位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. console.log(parentElement)完美地报告了两个子元素/节点,但是无论我做什么,后续的控制台日志(针对childNode的日志)总是返回undefined值。

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]相同的错误。

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 getElementsByClassName will 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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM