DarkCodeWiz DarkCodeWiz - 3 years ago 172
Javascript Question

Can't add NodeList custom method by prototype

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>


I'm getting "myList.addEvent is not a function" no matter what I try.

I had seen an example of how to achive this on MDN (middle of the page), source: https://developer.mozilla.org/en-US/docs/Web/API/NodeList

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);


EDIT:

Using .querySelectorAll() works for adding a prototype to a NodeList but not .getElementsByClassName(...)[0], .getElementsByTagName(...)[0] or .getElementById(...) - how come this only works on a static node list?

Answer Source

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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download