I want to create a helper function to aid iterating over child nodes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<ul class="list">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
NodeList.prototype.addEvent = func => {
for (let i = 0; i < this.length; i++) {
this[i].addEventListener('click', func)
}
}
let myList = document.getElementsByClassName('list')[0]
function test() {
console.log('Hello ', this[i].textContent())
}
myList.addEvent(test)
</script>
</body>
</html>
var elements = document.querySelectorAll(".suggestions");
NodeList.prototype.addEventListener = function(event, func) {
this.forEach(function(content, item) {
content.addEventListener(event, func);
});
}
function log() {
console.log(this, " was clicked");
}
elements.addEventListener("click", log);
Multiple issues with the code.
NodeList.prototype.AddEvent = function( func ) {
for (let i = 0; i < this.length; i++) {
this[i].addEventListener('click', func); //notice this[i] instead of this
}
}
var myList = document.querySelectorAll('.list'); //notice that element name is not .list so use querySelectorAll
myList.AddEvent(test); //addEvent to AddEvent
function test()
{
console.log('Hello')
}
<div class="list">
List div
</div>