use variable instead of string in createTextNode()

1.6k views Asked by At

I am trying to add another li to a ul via Javascript. I want the li to have dynamic content depending on an existing variable. I can get it to append a li using a string no problem. Only when I use a variable things go wrong

//Adding to List
listOfPlayers.style.display = "block";
var node = document.createElement("LI");
var textnode = document.createTextNode(playerInput.value);
node.appendChild(textnode);
listOfPlayersNumerated.appendChild(node);

The problem lays with:

var textnode = document.createTextNode(playerInput.value);

I have tried a literal string (as seen below) and it worked not problem

var textnode = document.createTextNode("New Player");
2

There are 2 answers

0
Ross Campbell On

So I changed it up so you can see where the variable is coming from...

Up top:

var inputPlayer = document.getElementById("inputPlayer");

Then I just add .value to get the value of that input below:

//Adding to List
listOfPlayers.style.display = "block";
var playerName = playerInput.value;
console.log(playerName);
var node = document.createElement("LI");
var textnode = document.createTextNode(playerName);
node.appendChild(textnode);
listOfPlayersNumerated.appendChild(node);

it will log it in the console but it does not appear on the ul

0
Ross Campbell On

Okay, I believe it did not like the scope. despite printing out the variable in the console. I moved

var playerName = playerInput.value;

Up and out of the current function. weird the console.log() would accept it but not .createTextNode() in that scope

So by moving where the new variable is declared outside the function it seems to have solved the issue