admin管理员组

文章数量:1325510

I am new to JavaScript and web development. I am trying to display contents of a few JavaScript arrays in html. From what I have read, using .innerHTML destroys all child elements.

I have 2 javascript arrays that I am querying from a REST API:

var humid=[10, 20, 30, 40];
var temp=[50, 60, 70, 80];

How do I display text in html that says, on each line:

Temperature was 10 degrees and humidity was 50%

Temperature was 20 degrees and humidity was 60%

... and so on.

Should I still use .innerHTML? If so, wouldn't it destroy all but the last line of the output? The output is being added to a <div> element, without a list or table.

I am new to JavaScript and web development. I am trying to display contents of a few JavaScript arrays in html. From what I have read, using .innerHTML destroys all child elements.

I have 2 javascript arrays that I am querying from a REST API:

var humid=[10, 20, 30, 40];
var temp=[50, 60, 70, 80];

How do I display text in html that says, on each line:

Temperature was 10 degrees and humidity was 50%

Temperature was 20 degrees and humidity was 60%

... and so on.

Should I still use .innerHTML? If so, wouldn't it destroy all but the last line of the output? The output is being added to a <div> element, without a list or table.

Share Improve this question edited Aug 26, 2017 at 13:41 user8446995 asked Aug 26, 2017 at 13:30 user8446995user8446995 1051 silver badge12 bronze badges 2
  • 3 Please create a minimal, concrete and verifiable example to illustrate your use case. It is not clear from your question how your DOM is structured: are you appending data to a list? A table? – Terry Commented Aug 26, 2017 at 13:31
  • 2 You could always create and append the new content so it doesn't remove the existing child elements... w3schools./JSREF/met_node_appendchild.asp – NewToJS Commented Aug 26, 2017 at 13:33
Add a ment  | 

7 Answers 7

Reset to default 3

There are several ways. First you could use appendChild with the createTextNode method. Or you can use innerHTML / innerText. Yeah you're right, they override all content, that is saved earlier, but... you can take the old content, append your new content and use innerHTML / innerText to set this bined content ;)

var humid=[10, 20, 30, 40];
var temp=[50, 60, 70, 80];

document.getElementById('output').innerHTML = document.getElementById('output').innerHTML + 'Temperature was '+humid[0]+' degrees and humidity was '+temp[0]+'%<br>';
// shorter:
document.getElementById('output').innerHTML += 'Temperature was '+humid[0]+' degrees and humidity was '+temp[0]+'%<br>';

If you want to append all:

var humid=[10, 20, 30, 40];
var temp=[50, 60, 70, 80];

for(i=0;i<humid.length;i++)
  document.getElementById('output').innerHTML += 'Temperature was '+humid[i]+' degrees and humidity was '+temp[i]+'%<br>';

This is the JS Implementation. Bees much easier when using jQuery. Let me know if you want help with Jquery implementation.

HTML

<div id="container"></div>

JS

var humid=[10, 20, 30, 40]; var temp=[50, 60, 70, 80];
var container = document.getElementById("container");
humid.forEach((item, index)=> {
   let newElement = document.createElement("p");
   let textNode = document.createTextNode("Temperature was "+temp[index]+" degrees and humidity was "+ item+"%")
   newElement.appendChild(textNode);
   container.appendChild(newElement);
;})

Simply you can prepare your final html content in variable then add it to your html

var humid=[10, 20, 30, 40]; 
var temp= [50, 60, 70, 80];
var text = "";
for (let i = 0; i < temp.length; i += 1) {
    text += `Temperature was ${humid[i]} degrees and humidity was ${temp[i]}% <br>`;
}
document.getElementById('output').innerHTML = text
<div id="output"></div>

var humid = [10, 20, 30, 40];
var temp = [50, 60, 70, 80];
var container = document.querySelector('.container');
for(var i=0; i<4; i++){
  container.innerHTML += `<p>Temperature was ${temp[i]} degrees and humidity was ${humid[i]} % `;
}
<div class="container">

</div>

It just sample code.

If you want to explain, ment please.

Using jQuery you can create new dom elements on the fly.

My proposal is to create a table and style it:

var humid = [10, 20, 30, 40];
var temp = [50, 60, 70, 80];

var table = $('<table/>')
        .append($('<thead/>').append($('<tr/>')
                .append($('<th/>', {text: 'Temperature was'}))
                .append($('<th/>', {text: 'degrees and humidity was'}))))
        .append($('<tbody/>'));
humid.forEach(function (ele, idx) {
    table.append($('<tr/>')
            .append($('<td/>', {text: ele}))
            .append($('<td/>', {text: temp[idx] + '%'})));
})
$(document.body).append(table);
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: center;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

There are a couple of answers. You can use innerHTML, but it means that you have to build up the HTML string by iterating over the arrays and concatenating the different outputs together. Something like this ES6 example which uses map.

function buildStr(temp, humid) {

  // Iterate over the array creating the string, returning a new array
  // with that string output
  return humid.map((el, i) => {
    return `Temperature was <b>${temp[i]}</b> degrees and humidity was <b>${humid[i]}</b>.`;

  // Joining that array of strings together with an html <br />
  }).join('<br />');
}

const main = document.querySelector('#main');
main.innerHTML = buildStr(temp, humid);

DEMO

For that to work in jQuery:

$('#main').html(buildStr(temp, humid));

Alternatively you can use insertAdjacentHTML. It has various ways to add HTML to existing elements, one of which is beforeend.

So, if you didn't want to iterate and wanted to add the HTML one line at a time:

const main = document.querySelector('#main');

let html = `Temperature was <b>${temp[0]}</b> degrees and humidity was <b>${humid[0]}</b>.`;
main.insertAdjacentHTML('beforeend', html);

let html2 = `Temperature was <b>${temp[0]}</b> degrees and humidity was <b>${humid[0]}</b>.`;
main.insertAdjacentHTML('beforeend', html2);

DEMO

In jQuery

<script>
$(document).ready(function(){
    var humid = [10, 20, 30, 40];
    var temp = [50, 60, 70, 80];

    $.each(humid, function( index, value ) {
      $("ol").append("<li>Temperature was "+value+" degrees and humidity was "+temp[index]+"%</li>");
    });
});
</script>

TAG

<ol>
</ol>

本文标签: jqueryJavaScript array content in html without innerHTMLStack Overflow