0

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"?

2
  • import the lobby.js in your html file and then print out the variable Commented Jan 23, 2021 at 20:07
  • If you want to change it in the current session only, then document.getElementById("lobbyCode").innerHTML = "abcdefg". If you want to change it permanently then this can only be done on the server. Commented Jan 23, 2021 at 20:08

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

6 Comments

When I tried this simply nothing happened, the screen displayed nothing at all. I know that the variable is keeping the data because if I simply send an "alert(lobbyCode);" it works fine. But when I use "document.getElementById("lobbyCode").innerHTML = code;" it displays nothing at all.
are your html file and the js file in the same directory? @MisterManFiveOFive
Yes, and I have added the js file to the html file as a part of the <head></head> section with the script tag format that you provided @Alex
then you need to create a <script></script> block in your html file and inside it you write this var lobbyCode = "abcdefg"; document.getElementById("lobbyCode").innerHTML = lobbyCode; I forgot to write it in my answer I have now updated it
Thank you for the quick responses! I have much more js code in lobby.js, and other js files aswell. So I was wondering if there was a way to update the span directly from the js file, as "lobbyCode" is actually a code that is generated from random letters and numbers in another js file. Is there any way I can do this? @Alex
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.