简体   繁体   中英

Is there any way to add a pre-specified element to a parent in JS?

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?

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>
 `);

}

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!
TheElement.append() method supports multiple arguments and appending strings.

Syntax
element.appendChild(aChild)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM