Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementById().textContent not working with variable

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

like image 406
Qwertie Avatar asked Dec 30 '13 05:12

Qwertie


1 Answers

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.

like image 133
adeneo Avatar answered Sep 27 '22 19:09

adeneo