質問

I'm trying to add an dynamically created element ( with document.createElement('span') ) inside an dynamically created div.

This is my code:

// Newplayer div holder
var newPlayer = document.createElement('div');
newPlayer.setAttribute('id', 'player_' + playerID);
newPlayer.setAttribute('class', 'player_entry');
newPlayer.setAttribute('style', 'background-color: ' + getRandomColor());

// Points holder
var playerTotalPointsHolder = document.createElement('div');
playerTotalPointsHolder.setAttribute('id', 'player_' + playerID + "_total_holder");
playerTotalPointsHolder.setAttribute('class', 'player_total_holder');

var playerTotalPoints = document.createElement('span');
playerTotalPoints.setAttribute('id', 'player_' + playerID + "_total");
playerTotalPoints.setAttribute('class', 'player_total');
playerTotalPoints.innerHTML = 0;

// Put the pieces together
playerTotalPointsHolder.innerHTML = "Total: " + playerTotalPoints;

But the output is:

Playername [object HTMLDivElement]

So my question is, how can i insert the element inside the element?

役に立ちましたか?

解決 2

Try changing this line:

playerTotalPointsHolder.innerHTML = "Total: " + playerTotalPoints;

to this:

playerTotalPointsHolder.appendChild(
  document.createTextNode('Total: ')
);
playerTotalPointsHolder.appendChild(
  playerTotalPoints
);

他のヒント

playerTotalPointsHolder.innerHTML = "Total: ";
playerTotalPointsHolder.appendChild(playerTotalPoints);

You need to use appendChild for this:

// Setting total score...
playerTotalPoints.innerHTML = "Total: " + 0;

// And pushing `span` to `div`
playerTotalPointsHolder.appendChild(playerTotalPoints);

With playerID 1, this will result in the following HTML:

<div id="player_1_total_holder" class="player_total_holder">
   <span id="player_1_total" class="player_total">Total: 0</span>
</div>

However, I suggest that instead of using span you should use p as paragraph for text. But even then, same principle applies for pushing element inside an element.

You created your elements but you didn't append them anywhere in your DOM. You need, at the end of your code, do something like this:

playerTotalPointsHolder.appendChild(playerTotalPoints);
newPlayer.appendChild(playerTotalPointsHolder);
someDOMElementInYourDocument.appendChild(newPlayer);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top