admin管理员组

文章数量:1389834

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>

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

Share Improve this question edited Jan 22, 2017 at 22:19 Tuğca Eker 1,49313 silver badges20 bronze badges asked Jan 22, 2017 at 22:13 Ryan StavRyan Stav 191 silver badge3 bronze badges 3
  • You can also use textContent if you're only updating text. – evolutionxbox Commented Jan 22, 2017 at 22:14
  • Does it work for you? – Brett DeWoody Commented Jan 22, 2017 at 22:21
  • This works. If it is not working for you, perhaps it is your browser. innerText is another similar to innerHTML. – Michael Bruce Commented Jan 22, 2017 at 22:22
Add a ment  | 

2 Answers 2

Reset to default 3

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>
With this code, you can have a text input that gets set to the variable 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 plicated, but it works, and it's all your code.

Not pletely. 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>

本文标签: How to update span element in HTML with javascript variableStack Overflow