Matthew Sirkin Matthew Sirkin - 1 month ago 4
HTML Question

Using Javascript generated HTML table yields undefined in my main div

I'm using a javascript to generate a table, and it is working and displaying my table, but for some reason there is also an undefined popping up in my viewer before the table and I don't know where it's coming from. I think it might be because my function is getting elements by the tag name "body" and my div is inside the body, and I'm using innerHTML on the div? but I've tried putting the div on the outside of the body and i've tried getting the elements by id names and I can't figure out how to get rid of the undefined. I just want my table to be generated inside a division so that I can create other divisions to put other content in. I don't just want the table generated in the body.

My HTML is:

<body>
<div id="eobody">

</div>
</body>


and my JS contains:

var body = document.getElementsByTagName("body")[0]; //to start building the table

document.getElementById("eobody").innerHTML = generate_table(paras1);
//runs the function that generates my table inside eobody


I've tried changing the body to div, and changed it to getting the element based on an ID, as well as putting the body inside a bigger division but I'm not really sure what's causing the undefined

Here's my fiddle that I'm working in https://jsfiddle.net/msirkin/duw5nyqe/8/
[Line 112, and Line 174 are the 2 lines I was talking about]

Answer

Looking at your JSFiddle, the generate_table() function doesn't return a value, so JavaScript's default return value of undefined is returned when you invoke the function.

Given that generate_table() does all the injecting at the end:

tbl.appendChild(tblHead);
document.getElementsByTagName("table").className = "tableizer-table";
tbl.appendChild(tblBody);
body.appendChild(tbl);

there is no need for you to inject anything to the div after invoking the function.

If you wanted to inject it in to your div you could use it as the appendChild() source element on the last line instead of body. e.g. document.getElementById('eobody').appendChild(tbl);