user11423796
user11423796

Reputation:

How can I change text in an html file using a javascript variable?

I have an html file "lobby.html" and a js file "lobby.js"

If this is in lobby.html,

<body>
    <span id="lobbyCode"></span>
</body>

And this is in lobby.js,

var lobbyCode = "abcdefg";

How can I make the html file display "abcdefg"?

Upvotes: 0

Views: 2768

Answers (1)

Aalexander
Aalexander

Reputation: 5004

In your html file you need to import the external js file.
Write the line below above your closing body tag to ensure it sees all the html elements.
Note: Consider that the path to your file at the src attribute value is based on your file structure.

<script src="lobby.js"></script> 
</body>

You can also put it in your header

<head> 
    <script src="lobby.js"></script> 
</head>

Then inside your external js file you are now able to access with the document.getElementById selector the inside your html file and you can update its value by setting the innerHTML property to the value of your variabel

external JS File

var lobbyCode = "abcdefg";
document.getElementById("lobbyCode").innerHTML = lobbyCode;

var lobbyCode = "abcdefg";
document.getElementById("lobbyCode").innerHTML = lobbyCode;
<body>
    <span id="lobbyCode"></span>
</body>

Upvotes: 3

Related Questions