Neesh
Neesh

Reputation: 87

use variable in .js and .html

I am making a website in html and I have an external .js file. There is a array in the .js file that I would like to display in the website as a list so will need to get the array into the html file but I do not know how to.

My html:

I would like the array in this tag

    <p id="demo"></p>

My external js:

    fruits = ["Banana", "Orange", "Apple", "Mango"];

Is there anyway to use the variable in the html file or can I display the array as a list in the js file?

Thanks in advance!

Upvotes: 0

Views: 61

Answers (1)

Get Off My Lawn
Get Off My Lawn

Reputation: 36311

It depends on how you want to display them, but mainly you want to use innerHTML to place them within the element.

let p = document.getElementById('demo');

let fruits = ["Banana", "Orange", "Apple", "Mango"];

p.innerHTML = fruits.join('<br>');
<p id="demo"></p>

You could also do it this way and make a unordered list:

let p = document.getElementById('demo');

let fruits = ["Banana", "Orange", "Apple", "Mango"];

p.innerHTML = fruits.map(i => `<li>${i}</li>`).join('');
<ul id="demo"></ul>

Upvotes: 2

Related Questions