Jacob F
Jacob F

Reputation: 147

How to append elements of array to DOM?

I am having trouble with adding elements to my HTML. I think my issue lies in my understanding of HTML but I'm not really sure. Here is my Javascript:

<div class="console">
    <div id="console_data">
        <p class="console_text"> </p>
    </div>
</div>

Let me explain what this is doing, or at least what I'm trying to do. The console class creates just a black rectangle, and it's gonna have some white text in it, which is what console_text is for. Here is my javascript to append things to console_data:

var consoleData = ["Hello World"]
var consoleInfo = document.getElementById('console_data')

for (var i = 0; i < consoleData; i++) {
    var anchor = document.createElement('a')
    var value = consoleData[i]
    anchor.href = value
    consoleInfo.appendChild(anchor)
}

I was under the impression this would append the text Hello World inside of the black box I created, but it's just showing the empty black box. Is my console_data tag even necessary? Where should I be trying to append my data to?

Upvotes: 2

Views: 841

Answers (1)

Spectric
Spectric

Reputation: 31987

You should be checking whether i is smaller than consoleData's length, since you are iterating through it:

var consoleData = ["Hello World"]
var consoleInfo = document.getElementById('console_data')

for (var i = 0; i < consoleData.length; i++) {
    var anchor = document.createElement('a')
    var value = consoleData[i]
    anchor.href = value
    anchor.innerHTML = value
    consoleInfo.appendChild(anchor)
}
<div class="console">
    <div id="console_data">
        <p class="console_text"> </p>
    </div>
</div>

Upvotes: 2

Related Questions