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">
<meta charset="UTF-8">
<ul class="list">

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


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


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() 
<div class="list">
  List div

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