1

Basically, I want to be able to add this code to the end of a parent div:

<br>
<div class="newPlayer">
  <h3>Player ${playerCount}</h3>
  <hr>
  <p>Name:</p>
  <input type="text" id="player${playerCount}"></input>
</div>

Here's what I'm currently using:

function newPlayer(){
  playerCount++;
  document.getElementById("players").innerHTML = document.getElementById("players").innerHTML + `<br><div class="newPlayer">
        <h3>Player ${playerCount}</h3>
        <hr>
        <p>Name:</p>
        <input type="text" id="player${playerCount}"></input>
      </div>`
}

Which works, but it refreshes all the inputs which is annoying. Any better methods?

Oliver
  • 23
  • 5
  • 1
    Yes. Either use [HTML Template](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template) or build the elements using the [DOM API](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) and then use [`.appendChild()`](https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild). `.innerHTML` should be avoided because it has security and performance implications. – Scott Marcus Apr 20 '21 at 19:59

2 Answers2

1

It might look something like this. Taking the createElement and Appendchild solutions.

function newPlayer(){
playerCount++;
document.getElementById("players").appendChild(document.createElement(`
   <br>
   <div class="newPlayer">
     <h3>Player ${playerCount}</h3>
     <hr>
     <p>Name:</p>
     <input type="text" id="player${playerCount}"></input>
   </div>
 `);

}

FujiRoyale
  • 762
  • 10
  • 26
  • 1
    It's saying that that's not a valid tag... P.S. You need another parentheses on the end too lol EDIT: Modified your code and it works (; – Oliver Apr 20 '21 at 22:37
  • Thanks for the help Oliver. I did not actually try running I was just getting as close as possible. – FujiRoyale Apr 20 '21 at 22:58
0

Of course! Check Element.appendChild

Node.appendChild()
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).

Newer API available!
The Element.append() method supports multiple arguments and appending strings.

Syntax
element.appendChild(aChild)

dbc
  • 104,963
  • 20
  • 228
  • 340
KletskovG
  • 520
  • 4
  • 10
  • A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](//meta.stackexchange.com/a/8259) so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. [Answers that are little more than a link may be deleted.](/help/deleted-answers) – 4b0 May 03 '21 at 10:34