获取直接第一个子元素 [英] Get immediate first child element

查看:32
本文介绍了获取直接第一个子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写 Chrome 内容脚本扩展程序,我需要能够定位一个特定元素,不幸的是,除了其父元素之外没有唯一标识符.

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.

我需要定位 parentElement 的第一个直接子元素.console.log(parentElement) 完美地报告了两个子元素/节点,但是后续的控制台日志(针对 childNode 的那些)总是返回一个 undefined 值,无论如何我做什么.

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.

这是我目前的代码
(我已经排除了实际名称以避免混淆和额外的、不必要的解释)

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);
    }   
}

如何选择parentElement的第一个子元素/节点?

How do I select the first child element/node of parentElement?

更新:
parentElement.children[0] 也有与 parentElement.childNodes[0] 相同的错误.

Update:
parentElement.children[0] also has the same error as 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]);

编辑

啊,我现在明白你的问题了;parentElement 是一个数组.

Ah, I see your problem now; parentElement is an array.

如果您知道 getElementsByClassName 只会返回一个结果,这似乎是你这样做,你应该使用 [0] 来整理(是的,我编造了这个词)元素:

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:

var parentElement = document.getElementsByClassName("uniqueClassName")[0];

这篇关于获取直接第一个子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆