简体   繁体   中英

Convert each Li element into an object

I have an unordered list of players for a game that is dynamically generated by the user on the page. What I want to do is turn each list item into an object that will allow me to store their name and points. Struggling with the code as I am still learning JS. I have got as far as the function to create each object but I don't know how to actual create an object for John, Paul, Ringo and George (or whoever else the user may add to the list)

<ul id="playerList">
     <li>John</li>
     <li>Paul</li>
     <li>Ringo</li>
     <li>George</li>
</ul>  

const createPlayer = (playerName, points) => {return {name, points}}

Here is how you would get each of those li contents from your html and then do whatever you want to do with those datas:

var numberOfPlayers = getElementsByTagName('li').length;
for (i=0 ; i< numberOfPlayers; i++) {
var playerData document.getElementById('playerList').getElementsByTagName('li')[i].innerText;
// create your objects or do whatever you want with playerData
}

Based on Yishmeray suggestion you could also do it like that, among your preferences:

var playerData = document.querySelectorAll('#playerList li'); 
playerData.forEach(element => { 
var thisPlayerTxt = element.innerText;
//create your objects or do whatever you want with playerData
});

And just in case you would like to create a li and append it to your list:

var list = document.getElementById('playerList');
var name = 'John';
var player = document.createElement('li');
player.innerText = name;
list.appendChild(player);

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