1

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

3
  • You can also use textContent if you're only updating text. Commented Jan 22, 2017 at 22:14
  • Does it work for you? 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. Commented Jan 22, 2017 at 22:22

2 Answers 2

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 complicated, but it works, and it's all your code.

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

Comments

2

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>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.