简体   繁体   中英

How to reach last element in forEach() JS

I have tried lots of solutions here but non worked for me. I'm looping node elements, and I want to get to the last one so I update it.

app.js

var userLen = document.querySelectorAll('.username').length
document.querySelectorAll('.username').forEach(function (event) {
  event[event === (userLen - 1)].innerHTML =   window.localStorage.getItem('micky')
})

I get this error every time Uncaught TypeError: Cannot set property 'innerHTML' of undefined.

You don't need to loop over element to reach the last one.

Moreover, you are trying to get event[true] or event[false] as event === (userLen - 1) will return a boolean, not an actual index.

Try this:

var nodeElememnts = document.querySelectorAll('.username');
if(nodeElements.length > 0){
    nodeElements[nodeElements.length - 1].innerHTML = window.localStorage.getItem('micky');
}

You can do this w/o using forEach here like:

 var elm = document.querySelectorAll('.username'); var lastElem = [].slice.call(elm).pop(); if (lastElem) lastElem.innerHTML = 'It Works!'; // For debugging purpose console.log( [].slice.call(elm) ) //<-- Convert NodeList to Array console.log( lastElem ) 
 <div class="username">A</div> <div class="username">B</div> <div class="username">C</div> 

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