createTextNode/appendChild using an array

6.4k views Asked by At

I am trying to print out all of my array items in a table like manner. I'm creating a <th> tag for the headers, and a <tr> tag for each element within the array (seperate from the headers array). Whenever I try and do this, I get the expected result with the exception that all of array elements are just one long string. So i get something like this:

Site 1 Site 2 Site 3 Site 4
1,2,3,4,5,6

and I want it to return:

Site 1 Site 2 Site 3 Site 4
1
2
3
4
5

I have tried doing the .join('\n') but it is not working

Code:

    //Print Items in Level1
var createLevel1CellTag = document.createElement('td');
createLevel1CellTag.id = 'Level1';
var Level1TextNode = document.createTextNode(Level1Items.join('\n'));
createLevel1CellTag.appendChild(Level1TextNode);
document.getElementById('theHeaderTag0').appendChild(createLevel1CellTag);

I can do it using a for loop but then when I go to create the element Id, it just overwrites it. So when I go to use my onmouseover/onmouseout functions, it only hides/shows 1 of the array elements. Maybe the question is how do I reference all of those ID's that are created within the for loop. So I loop the creation of the ID and then how do I reference Level1x?

1

There are 1 answers

1
user2736012 On BEST ANSWER

With respect to the line breaks, in the DOM, a line break is represented by a <br> element, not a \n character. So you should loop over the Array, and add a text node followed by a <br>.

var header = document.getElementById('theHeaderTag0');
var createLevel1CellTag = header.appendChild(document.createElement('td'));
createLevel1CellTag.id = 'Level1';

for (var i = 0; i < Level1Items.length; i++) {
    createLevel1CellTag.appendChild(document.createTextNode(Level1Items[i]));
    createLevel1CellTag.appendChild(document.createElement("br"));
}

I don't entirely follow your alternate question about selecting by ID.