最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - document.getElementById().textContent not working with variable - Stack Overflow

programmeradmin5浏览0评论

When I use document.getElementById().textContent to set the "text content" to the value of a variable it doesn't work it doesn't to anything instead changing the text content to the value of the variable. It does work when I use

.textContent = "example";

but not

.textContent = example;

Here is my HTML

<head>
   <link rel="stylesheet" type="text/css" href="style.css">
   <script language="javascript" type="text/javascript" src="testScript.js"></script>
</head>

<body>
   <p class="heading">Heading</p>
   <p id="TextSpace"></p>


</body>

Here is my JS

//Get users name
var name = prompt("What is you name");
//put the name in the element "text space"
document.getElementById("TextSpace").textContent = name;

The prompt appears but after that nothing happens

When I use document.getElementById().textContent to set the "text content" to the value of a variable it doesn't work it doesn't to anything instead changing the text content to the value of the variable. It does work when I use

.textContent = "example";

but not

.textContent = example;

Here is my HTML

<head>
   <link rel="stylesheet" type="text/css" href="style.css">
   <script language="javascript" type="text/javascript" src="testScript.js"></script>
</head>

<body>
   <p class="heading">Heading</p>
   <p id="TextSpace"></p>


</body>

Here is my JS

//Get users name
var name = prompt("What is you name");
//put the name in the element "text space"
document.getElementById("TextSpace").textContent = name;

The prompt appears but after that nothing happens

Share Improve this question asked Dec 30, 2013 at 5:11 QwertieQwertie 6,53314 gold badges52 silver badges102 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

Move the script

<head>
   <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
   <p class="heading">Heading</p>
   <p id="TextSpace"></p>

   <script language="javascript" type="text/javascript" src="testScript.js"></script>
</body>

or add an onload handler

window.onload = function() {
    var name = prompt("What is you name");
    document.getElementById("TextSpace").textContent = name;
}

Right now the script is running before the elements in the DOM are available.
Note that textContent is not available in IE8 and below.

Instead of putting the script tag at the bottom, you can just put defer and it will work perfectly fine

<head>
   <link rel="stylesheet" type="text/css" href="style.css">
   <script language="javascript" type="text/javascript" src="testScript.js" defer></script>
</head>

<body>
   <p class="heading">Heading</p>
   <p id="TextSpace"></p>


</body>

发布评论

评论列表(0)

  1. 暂无评论