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.
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With