Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

javascript - 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.

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.

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?

enter image description here

Update:
parentElement.children[0] also has the same error as parentElement.childNodes[0].

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...