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
2 Answers
Reset to default 3It 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
版权声明:本文标题:How to update span element in HTML with javascript variable? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744664042a2618422.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论