0

I am having trouble appending an array called phrases to a method called addPhraseToDisplay(). Here is the array:

class Game {
constructor() {
    this.missed = 0; // this property will be used as a counter for the total of 5 tries
    this.phrases = ["life is strange","success does not come easy", "seven swans swimming", "guess the word", "wild goose chase"] 
}

what I want to do is append the array into as list items, I tried to target the phrases like this newListItem.textContent = (this.phrases);, but that didn't work

addPhraseToDisplay() {
   //Create a reference to ul element
    const myList = document.getElementById('myList');

    //Crete new list items
    let newListItem = document.createElement('li');
    newListItem.textContent = (this.phrases);

this is html code where I would like the array to be inside as list items

<!--My phrases need to be appended down here, div is parent element -->
        <div id="phrase" class="section">
            <ul id="myList">

            </ul>

if someone could help I would appreciated

ZachB
  • 13,051
  • 4
  • 61
  • 89
Erik L
  • 195
  • 1
  • 2
  • 18
  • Possible duplicate of [Link](https://stackoverflow.com/questions/11128700/create-a-ul-and-fill-it-based-on-a-passed-array), I hope this useful for you – Moumen Soliman Nov 30 '18 at 16:44

2 Answers2

0

Hello you can try this:

<html>
<body>

<div id="myList">

</div>

<p>Click the button to append an item to the end of the list.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    //Creating element with html tag .... and append it to another element
    var node = document.createElement("UL");
    var textnode = document.createTextNode("Water");
    node.appendChild(textnode);
    document.getElementById("myList").appendChild(node);
}
</script>


</body>

Hope this it exactly what are you looking for.

  • Thanks for trying to help, but what I am looking to do ia put the array as list items, not just add a single letter – Erik L Dec 01 '18 at 00:16
  • Single letter did you what's the result of this, and you only should use this with a FOR loop ? – xXManiakaXx Dec 11 '18 at 17:42
0
<html>
<body>

<ul id="myList">

</ul>

<p>Click the button to append the array to the end of the list.</p>

<button onclick="myFunction()">Try it</button>

<script>
var myPhrases = ["Phrase 1", "Phrase 2", "Phrase 3", "Phrase 4", "Phrase 5"]
function myFunction() {
    //Creating element with html tag .... and append it to another element
    for (i = 0; i < myPhrases.length; i++)
    {
      var node = document.createElement("li");
      var textnode = document.createTextNode(myPhrases[i]);
      node.appendChild(textnode);
      document.getElementById("myList").appendChild(node);
    }
}

</script>


</body>

Previous example with for loop.