-1

I'm trying to create a JavaScript function that allows me with a click to save the last element of an array (standbyWord array) and then have that saved element appear as an HTML <li>.

I have managed to change the innerHTML, so each time the save button is clicked the last element from the standbyWord array is saved in the savedWords array. However, I would like that each time the save button is pushed a new <li> appears with that new saved word.

<div>
  <ul>
     <li id="listWord"></li>
  </ul>
</div>

let savedWords = [];

function saveWord(){
      savedWords.push(standbyWord[standbyWord.length - 1]);
      document.getElementById('savedWordCount').innerHTML = savedWords.length;
      document.getElementById('listWord').innerHTML = savedWords;
    }
1
  • have you tried the appendChild() method on html elements? appendChild() Also, your example code is incomplete, please insert full examples with save button and standbyWord variable. Commented Sep 24, 2020 at 10:07

1 Answer 1

1

If you want to use innerHTML, you need to be aware that this will replace the entire inner contents of the tag - as your code stands, you will just end up with a string of words BUT, if you want them to be within li tags, you would have li tags within an li whereas they should be within a ul or ol tag . If you change your ul element to have the id="listword" and remove the li tag, you can do:

let savedwords = ["cat","dog", "rabbit", "horse", "donkey", "whale", "mouse"];

let lw = document.getElementById("listword");
lw.innerHTML = "<li>" + savedwords.join("</li><li>") + "</li>";
<div>
  <ul id="listword">
  
  
  </ul>

</div>

Or, you could do as @JustAMicrobe suggests and create a new li object for just the new word and append that to the ul object using appendChild.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.