Search code examples
getelementsbytagnamegetelementsbyclassnamenodelisthtmlcollection

How can an nodelist created by getElementsByClassname or getElementsByTagName display its values as string


What I know about getElementsByClassName / getElementsByTagName is that both create a nodelist of the elements in question and that the nodelist elements are treated as objects I have a problem where I want to display the innerHTML of the elements inside of the nodelist but because they are objects this seems to be impossible.

Example:

<!DOCTYPE html>
<head>
    <link rel="stylesheet" type="text/css"  href="stylesheet.css">
    <script src="javascript.js"></script>
</head>
    <body>
        <p id="pp"></p>
        <button onclick="test()">push to test</button>
        <p>dog</p>
        <p>cat</p>
        <p>snake</p>
    </body>

//javascript.js file

function test() {
    var paragraph = document.getElementsByTagName("p"),
        para1 = paragraph[0].innerHTML,
        ansBox = document.getElementById("pp");
    ansBox.innerHTML = para1;
}

This is condensed version of a longer code. I think that the para1 variable should be a string and then the assignment statement should assign that string to the ansBox.innerHTML but instead I get nothing. I have reworked several versions of this code none work. How can you get the text elements inside of a nodelist to display in the ansBox?


Solution

  • Your script is loaded but your DOM hasn't loaded yet if you load your script inside head like that

    <!DOCTYPE html>
    <head>
        <link rel="stylesheet" type="text/css"  href="stylesheet.css">
    </head>
        <body>
            <p id="pp"></p>
            <button onclick="test()">push to test</button>
            <p>dog</p>
            <p>cat</p>
            <p>snake</p>
            <script src="javascript.js"></script> <!-- load it here -->
        </body>
    

    Also paragraph[0] and ansBox refer to the same DOM HTMLParagraphElement just so you know which does not have anything inside (It is empty to begin with)