admin管理员组

文章数量:1394740

I am working on a spelling game for my children, and I want to display a spelling list based on what they enter and an array that is created. Here is the link to my project on github .git

Here is the code in question, javascript first

function populateSpellList() {      
    // for loop should run through spelling list array and create list items in "listSpelling"

    for (var i = 0; i < spellingList.length; i++ ) {
        // create a new li
        var newLI = document.createElement("li");
        var indSpellingWord = spellingList[i];

        // grab the spelling list item 
        var newContent = document.createTextNode(indSpellingWord);

        // add the spelling list item to the li
        newLI.appendChild(newContent);

        // get the unordered list and add the new li
        var displaySpellList = document.getElementById("listSpelling");     

        displaySpellList.appendChild(newLI);
    }   
}

And the HTML

<div id = "theSpellingList">

            <h3>The Spelling List</h3>
            <ul id = "listSpelling">
               <li>test </li>
            </ul>

        </div>

I can get an alert to pop up for me after every line in the function except the last, and it only seems to pop up once. But no matter what happens it is not displaying any list items in that list.

I have seen a lot of jquery examples on here so I am definitely going to be pursuing learning jquery, but for now "plain" javascript would be great.

I am working on a spelling game for my children, and I want to display a spelling list based on what they enter and an array that is created. Here is the link to my project on github https://github./urock24/myWebSite.git

Here is the code in question, javascript first

function populateSpellList() {      
    // for loop should run through spelling list array and create list items in "listSpelling"

    for (var i = 0; i < spellingList.length; i++ ) {
        // create a new li
        var newLI = document.createElement("li");
        var indSpellingWord = spellingList[i];

        // grab the spelling list item 
        var newContent = document.createTextNode(indSpellingWord);

        // add the spelling list item to the li
        newLI.appendChild(newContent);

        // get the unordered list and add the new li
        var displaySpellList = document.getElementById("listSpelling");     

        displaySpellList.appendChild(newLI);
    }   
}

And the HTML

<div id = "theSpellingList">

            <h3>The Spelling List</h3>
            <ul id = "listSpelling">
               <li>test </li>
            </ul>

        </div>

I can get an alert to pop up for me after every line in the function except the last, and it only seems to pop up once. But no matter what happens it is not displaying any list items in that list.

I have seen a lot of jquery examples on here so I am definitely going to be pursuing learning jquery, but for now "plain" javascript would be great.

Share Improve this question edited Jan 29, 2015 at 1:52 Paul 27.5k13 gold badges89 silver badges126 bronze badges asked Jan 29, 2015 at 1:41 urock24urock24 1452 gold badges3 silver badges9 bronze badges 3
  • And how do you call it? (I doubt anyone is going to go through all those files to find the code) – epascarello Commented Jan 29, 2015 at 1:46
  • 1 It works for me: jsfiddle/hjzp1y31 – Barmar Commented Jan 29, 2015 at 1:50
  • From a search of your github for "spellingList" it appears it is never set to any list, as in @Barmar's fiddle. – Paul Commented Jan 29, 2015 at 2:03
Add a ment  | 

4 Answers 4

Reset to default 4

From what I can see, you're trying to insert elements into the document which is embeded via iFrame. But you can't do this that simple. The thing is that when you call document.getElementById from the parent (not iframe) window, it tries to find an element within parent window. But iFrame is a separate window.

You can try following.

In every specific game html file:

<body>
  <!-- SOME CONTENT HERE -->

  <!-- RIGHT BEFORE `BODY` CLOSE -->
  <script>
    // This will run your code once document is loaded.
    window.onload = function () {
        // run the createName function
        createName();
        // run the createList function 
        createList();
        //play game
        playGame(target);
    };
  </script>
</body>

In learningGames.js:

function populateSpellList() {  

    // for loop should run through spelling list array and create list items in "listSpelling"
    var i;
    for (i = 0; i < spellingList.length; i++ ) {

        var newLI = document.createElement("li"), // create a new li
            displaySpellList = document.getElementById("listSpelling"), // cache the unordered list
            newContent = document.createTextNode(spellingList[i]); // grab the spelling list item

        // add the spelling list item to the li
        newLI.appendChild(newContent);

        displaySpellList.appendChild(newLI);
    }
}

function gameWindow(target) {
    // set the iframe html to the target html 
    document.getElementById('game_frame').src = target;
}

Hope it is exactly what you need.

More of a ment than answer, your basic code seems to work fine with some added test data. Below are some suggestions on making the code a little more concise:

<script>

// List of words
var spellingList = ['foo','bar','fum'];

function populateSpellList() {

  // Get list once and store reference
  var list = document.getElementById("listSpelling");

  // Declare variables once, near top is good
  var li;

  // for loop should run through spelling list array and create list items in "listSpelling"
  for (var i = 0; i < spellingList.length; i++ ) {

    // Create new LI
    li = document.createElement("li");

    // Append the spelling word
    li.appendChild(document.createTextNode(spellingList[i]));

    // Add to list
    list.appendChild(li);
  }
}

// Call the function when the document is ready
window.onload = populateSpellList;
</script>

<div id = "theSpellingList">
  <h3>The Spelling List</h3>
  <ul id = "listSpelling">
    <li>test </li>
  </ul>
</div>

You can do the above in fewer lines of code, however it bees a bit unmanageable. Less code isn't always "better".

  • Pass your array items as argument to your function
  • Use Element.insertAdjacentHTML() with the "beforeend" arg
  • Use Array.prototype.reduce() to reduce an array to a String HTML

const populateSpellList = (items) => { 
  document.querySelector("#listSpelling").insertAdjacentHTML(
    "beforeend",
    items.reduce((acc, item) => acc += `<li>${item}</li>`, "")
  );
};

populateSpellList(["Word1", "Word2", "Word3"]);
<ul id="listSpelling"><li>test</li></ul>

You could do this. Make sure your JS is placed after the HTML, or put it in a window.onload function.

var listEl = document.getElementById('listSpelling');

var spellingList = ['word1', 'word2', 'word3', 'word4'];

var populateList = function(arr){
    var str = '';
    for(var i = 0; i < arr.length; i++){
        str += '<li>' + arr[i] + '</li>';
    }
    return str;
}

listEl.innerHTML = populateList(spellingList);

Fiddle

本文标签: Javascript add li to ul using arrayStack Overflow