When i create an element using createElement then appendChild i can't access them using eventListener.
In this case
<div class="row">
<ul class="maldito mt-5">
</ul>
</div>
After i add the li element i can't target it with eventListener
var $ul = document.querySelector('.maldito');
var $li = $ul.querySelectorAll('li');
(function(){
var x = 0;
while ( x < 2) {
x++;
var addLi = document.createElement('li');
$ul.appendChild(addLi);
}
$li = $ul.querySelectorAll('li');
for ( var i = 0; i < $li.length; i++ ){
$li[i].textContent = "Some text";
}
window.addEventListener('DOMContentLoaded', function(){
for ( var i = 0; i < addLi.length; i ){
addLi[i].addEventListener('click', function(){
this.classList.add('active');
})
}
})
})()
You should either keep a reference to the element or access the element the event handler was attached to through Event#currentTarget
.
const app = document.getElementById("app"); const words = [ "hello", "world", "foo", "bar" ]; // Map words to array of HTMLElements const wordElements = words.map(w => { const el = document.createElement("div"); el.innerHTML = w; return el; }); // Append elements after we have created them // Even though "el" reference is gone wordElements.forEach(we => app.appendChild(we)); // Even add event listener later wordElements.forEach(we => { we.addEventListener("click", e => { console.log(`Through el reference: ${we.innerHTML}`); console.log(`Through currentTarget: ${e.currentTarget.innerHTML}`); }); });
<div id="app"></div>
You need to push your new li element into an array ( lis
on my example)
var $ul = document.querySelector('.maldito'); var $li = $ul.querySelectorAll('li'); let lis = [];// li elements array (function(){ var x = 0; while ( x < 2) { x++; var addLi = document.createElement('li'); $ul.appendChild(addLi); lis.push(addLi);// push the li element into the lis array } // $li = $ul.querySelectorAll('li'); for ( var i = 0; i < lis.length; i++ ){ lis[i].textContent = "Some text"; } window.addEventListener('DOMContentLoaded', function(){ //console.log(lis.length) for ( var i = 0; i < lis.length; i++ ){ lis[i].addEventListener('click', function(){ this.classList.add('active'); }) } }) })()
.active{color:red}
<div class="row"> <ul class="maldito mt-5"> </ul> </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.