I'm trying to update a span element to show my javascript variable is this correct?
var hometown = "Indianapolis" ;
document.getElementById('hometown').innerHTML = 'Indianapolis';
Hometown: <span id="hometown"></span>
thanks for any help
It is basically correct except that you never use your variable, so there is no point to the variable. If you want to use the variable to change it you can do this instead.
var hometown = "Indianapolis";
document.getElementById('hometown').innerHTML = hometown;
Hometown: <span id="hometown"></span>
hometown, like this.
function update() {
var hometown = document.getElementById("text").value;
document.getElementById("hometown").innerHTML = hometown;
}
Hometown: <span id="hometown"></span>
<br>
<input type="text" id="text">
<input type="button" onClick="update()" value="Update">
I know this one is a little complicated, but it works, and it's all your code.
Not completely. You are not using the variable.
document.getElementById('hometown').innerHTML = hometown;
Since you are not setting html content, using .textContent property is a better option:
document.getElementById('hometown').textContent = hometown;
Also make sure that element is added to DOM before selecting it, i.e. put the script after the target span element.
Hometown: <span id="hometown"></span>
<script> /* JavaScript code goes here */ </script>
textContentif you're only updating text.