Hey suppose I have code like:

<td id="something">I want to put stuff in here</td>

How would I be able to put the value of a JavaScript array into the part where I want to put stuff. Say the value of the array at a position is hello, I would output hello.

Dani AI

Generated

Short answer: grab the table cell by its id and assign the array element to the element's text content (or innerHTML if you need markup). Make sure the DOM element exists before you write to it (run after DOMContentLoaded or place the script after the table).

Example — set one cell and also populate a series of cells named with a numeric suffix:

document.addEventListener('DOMContentLoaded', function () {
  var data = ['Text', 'Hello', 'Third'];
  var single = document.getElementById('cell0');               // single cell
  if (single) single.textContent = data[0];

  // populate cell0, cell1, cell2 ... if those IDs exist
  data.forEach(function (value, i) {
    var el = document.getElementById('cell' + i);
    if (el) el.textContent = value;
  });
});

Notes and gotchas: use textContent for plain text (safer and avoids accidental HTML parsing). Use innerHTML only when you intentionally want to insert markup and the content is trusted or properly sanitized. Always check the element exists before writing to it to avoid runtime errors. IDs must be unique — if you have many cells consider using classes or querySelectorAll and mapping array values to elements by index. If your script runs before the table is parsed, wrap it in DOMContentLoaded (as above) or move the script tag to the end of the body.

As suggested, you do not need a form for this; DOM methods are the right tool. For reference see Document.getElementById and Node.textContent. This approach will display data[0] (the example "Text") in the targeted table cell for .

Recommended Answers

All 2 Replies

Using a form would be one approach. Are you trying to avoid the use of forms?

Alternately, you could try innerHTML. Put a div or span where results are to be inserted and then write the Javascript code such that it outputs the appropriate HTML.

Well say I have an array that has a value of "Text" at position 0. How would I set the array at position 0 to display in my table where I have the element x.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.