Problem with Looping through over a newly created list element by js

javascript loop through array of objects
javascript for loop
loop through two arrays javascript
js loop through a list
loop through object javascript
javascript foreach object
javascript loop through array of objects es6
loop through array java

I am building a Todo-List Project and i am stuck at looping through my newly created list items.

This is what i am doing:

  1. Created an array.
  2. Made li items for array's each element through looping so that array appears in a list manner.
  3. And then looping through newly created li section to addEventListener on each of li's ( But this one is not working).

 var arrList = ["play","learn","walk"];
 var list = document.querySelectorAll("li");
 var done = false;

//printing array in list manner
for(let i = 0; i < arrList.length; i++){
    let el = document.createElement("li")
    el.textContent = arrList[i];
    document.querySelector("ul").appendChild(el);
}
//looping through each li's to apply if else statement
 for(let i = 0; i < list.length; i++){
    list[i].addEventListener("click",function(){
        if(!done){
            this.style.textDecoration = "line-through";
            done = true;
        }else{
            this.style.textDecoration = "none";
            done = false;
        }
    })
}

You're code is mostly correct, however there are a few issues that need to be addressed. First, consider replacing your for loop with iteration based on forEach() as shown below. Using forEach() in this way allows you to leverage "closure" which in this case will greatly simplify your code. For instance, you can use the closure feature to store the done state of each item in your list, rather than storing that state explicitly in an array.

The other issue I noticed was var list = document.querySelectorAll("li"); queries the document for li elements before any are added to your document - later in your script it seems you're iterating that empty query result and expecting it to contain the added li elements.

Here's a working snippet - hope this helps!

var arrList = ["play", "learn", "walk"]; 

// Iterate the list via forEach
arrList.forEach(function(arrItem) {

  // We're now in a new "closure" for this list item 
  // so we can define some state like "done" that will
  // be used exclusively for this list item
  var done = false;

  // Create li element for this list item as before
  var el = document.createElement("li")
  el.textContent = arrItem;

  // Configure click event
  el.addEventListener("click", function() {

    // Notice we're able to use the done variable
    // in this closure for this list item? The key
    // thing to understand is that each list item
    // will have it's own unique "done" variable
    if (!done) {
      el.style.textDecoration = "line-through";
      done = true;
    } else {
      el.style.textDecoration = "none";
      done = false;
    }
  })

  document.querySelector("ul").appendChild(el);
});
<ul></ul>

Beginning JavaScript with DOM Scripting and Ajax: From Novice to , The utility method checkValue() adds new elements to the error array if there are appendChild( entry ); } Loop through the error array and create a new list item  Assuming you have initiated a new Vue Instance and have associated it with the element of id app {{n}} var app = new Vue({ el: '#app', }); Notice the new directive v-for, we can loop through a list using v-for directive and specifying the item in items where an item is the current iteration and items are the total number of items in the list


It seems like you only have one done variable that is shared for every item on the todo list. Therefore if you click one of the items all of the items will be crossed out. You will need a boolean variable for every item in your to do list.

Looping JavaScript Arrays Using for, forEach & More ‍ , JavaScript for loops iterate over each item in an array. For instance, when you want to create a new variable within the loop, forEach creates a new instance, This is great when you want to loop through the list in order. Fortunately, I could not have this problem because I was using associative arrays. Looping through objects in JavaScript 20th Jun 2018. Once in a while, you may need to loop through Objects in JavaScript. The only way to do so before ES6 is with a forin loop. The problem with a forin loop is that it iterates through properties in the Prototype chain.


Add this line just above the second for loop and remove from the top.

var list = document.querySelectorAll("li");

You are assigning list the values even before they are created.

New Perspectives on HTML, XHTML, and Dynamic HTML: Comprehensive, HTML 563—604 accessing external JavaScript files, HTML 590—594 applying filter See conditional statement creating date and time variables, HTML 623 See program loop running commands as hypertext links, HTML 622 script element, HTML 93—94 URLs, HTML 89-90 Web sites, HTML 90—92 list, HTML 22-27,  Looping through a List of objects in JavaScript Tag: javascript , angularjs I want to loop through the student list which I received from a REST service located on a server. this list contains objects for students enrolled in a section.


from the source code I see that the list li item is initialized before new li item been created, it will cause the list li item not contains the new one, due to that addEventListener will not working for the new item.

to fix this, just need move init list li item code after creation part :

    var arrList = ["play","learn","walk"];
    var done = false;

    //printing array in list manner
    for(let i = 0; i < arrList.length; i++){
        let el = document.createElement("li")
        el.textContent = arrList[i];
        document.querySelector("ul").appendChild(el);
    }

    var list = document.querySelectorAll("li");
    //looping through each li's to apply if else statement
    for(let i = 0; i < list.length; i++){
        list[i].addEventListener("click",function(){
            if(!done){
                this.style.textDecoration = "line-through";
                done = true;
            }else{
               this.style.textDecoration = "none";
               done = false;
            }
        })
    }

Beginning JavaScript with DOM Scripting and Ajax: Second Editon, removeChild(parent); i--; } You create a new list element and add the badge class to (You loop through all the links of the document, which means that when you container) { var request; try { request = new XMLHttpRequest(); } catch (error)  initialization - Run before the first execution on the loop. This expression is commonly used to create counters. Variables created here are scoped to the loop. Once the loop has finished it’s execution they are destroyed. condition - Expression that is checked prior to the execution of every iteration. If omitted, this expression evaluates


Please, be simple...

var
  arrList    = ["play","learn","walk"],
  UL_arrList = document.querySelector("ul")
  ;

arrList.forEach (arrItem => {
  let el = document.createElement("li");

  el.textContent = arrItem;
  UL_arrList.appendChild(el);

  el.onclick = function(e){
    let deco = this.style.textDecoration || 'none';
    this.style.textDecoration = (deco==='none') ? 'line-through': 'none';
  }
});
<ul></ul>

JavaScript Cookbook, However, in the first loop iteration, once the first element has been moved (in is moved to the bulleted list using appendChild on a newly created list element Existing. Table. Problem. You want to add one or more rows to an HTML table. It will return items where the callback method returns true. But it will also iterate over all the items, even if you have the right element(s) already. There are scenarios where forEach adds value. For instance, when you want to create a new variable within the loop, forEach creates a new instance, where the for loop will assign a new value.


Master the art of looping in JavaScript with these incredible tricks, Many times in your code you require to loop through an array of numbers method which helps you loop through arrays, objects, DOM elements, JSON & XML quite easily. The above JavaScript code will create a new row containing the total price of the product. Python List Append What is Chromium? The map() method creates a new array with the results of calling a provided function on every element in the calling array. So the map function was introduced to JavaScript in ES2015.


Ways of iterating over a array in JavaScript., Polynomial Time Approximation Scheme · A Time Complexity Question There are multiple ways one can iterate over an array in Javascript. using forEach method. A map applies a function over every element and then returns the new array. How to Create a Dropdown List with Array Values using JavaScript ? The problem with dynamically created elements, is that they aren’t born with the same event handlers as the existing elements. Let’s say we have a list of items that you could click on to toggle/add a class name, when a new element is created and appended to that same list - it won’t work - the event handler attachment is missing.


JavaScript for Loop, The For/Of Loop. The JavaScript for/of statement loops through the values of an iterable objects. for/of lets you loop over data structures  Method 2: Looping through the parents of the given child The child can be checked to have the given parent by continuously looping through the element’s parents one by one. The parent of each node is found by accessing the parentNode property which returns the parent node if any.