Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS not working with HTML (basic)

To start, I'm a bit of a novice. I've been trying to create a JS file to contain all my text variables to use in my HTML file(among other functions). My JS file is located in the same directory as my HTML file (C:/websites/first). My CSS file has linked and works properly, confusing me on why this isn't working.

I've tried working with answers from these posts and a few others, with no luck:

Set content of HTML <span> with Javascript

How do I change the text of a span element in JavaScript

How to pass Variable from External JavaScript to HTML Form

What I'm trying to do here is set my

to contain my fullname var. Once I get this the rest of my problems should be resolved too.

here's a snippet of my JS:

    var fullname = "example";
    document.getElementById('fullname').innerHTML = fullname;

and a snippet of my HTML:

    <html>
     <head>
        <script type="text/javascript" src="script.js"></script>
     </head>
     <body>
        <p id="fullname"></p>
     </body>
    </html>

I can't find what i'm doing wrong. I've been ripping my hair out because it is so simple but I haven't found a solution.

like image 205
user3524785 Avatar asked Apr 30 '26 03:04

user3524785


1 Answers

Put the script after the elements in the DOM, otherwise the elements doesn't exist when you're trying to get them

<html>
    <head>
    </head>
    <body>
        <p id="fullname"></p>
        <script type="text/javascript" src="script.js"></script>
    </body>
</html>

Another (not as good) option is waiting for onload

window.onload = function() {
    var fullname = "example";
    document.getElementById('fullname').innerHTML = fullname;
}

or in modern browsers

document.addEventListener("DOMContentLoaded", function(event) {
    var fullname = "example";
    document.getElementById('fullname').innerHTML = fullname;
});
like image 161
adeneo Avatar answered May 01 '26 17:05

adeneo