Hypothetically, say I have an array named "fruits" which included different fruits. Something that looks like this:
var fruits = ["bannanna", "apple", "orange", "grapes"]
I want to create an h1 element with each of of the names in the array. How do I do this?
Loop over the items, and use insertAdjacentHTML to add the item to the body or where ever you want to add it.
var fruits = ["bannanna", "apple", "orange", "grapes"] fruits.forEach(item => document.body.insertAdjacentHTML('beforeend', `<h1>${item}</h1>`))
you can do it by through forEach.
<div id="generate-h1"></div>
var fruits = ["bannanna", "apple", "orange", "grapes"]
// Create any HTML Element to put H1 Tags into this HTML Tag
var main = document.createElement('main');
// Create H1 items for each fruits
// Append it to the main Tag or whatever you have.
fruits.forEach(function (fruits) {
var headline = document.createElement('h1');
headline.textContent = fruits;
main.appendChild(headline);
});
// Inject into the DOM
var app = document.querySelector('#generate-h1');
app.appendChild(main);
Okay try this I am sure this will work:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Try This</title>
</head>
<body>
<h1 id="fruit"></h1>
<script>
var fruits = ["bannanna", "apple", "orange", "grapes"];
var text = "";
var i;
for (i = 0; i < fruits.length; i++) {
text += fruits[i] + "<br>";
}
document.getElementById("fruit").innerHTML = text;
</script>
</body>
</html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.