I am using two classes in javascript.
class Challenge and class Modules, that extends Challenge.
in Challenge i have this constructor:
constructor() {
this.handles = [];
}
and this method:
bla() {
let elmnts = document.querySelectorAll("p"); // 5x
for(let i=0; i < elmnts.length; i++) {
let elmnt = elmnts[i];
this.handles[elmnt['id']] = elmnt; // saves the handles to each element in separate array for later use
}
}
in the child Class i am trying to use this "this.handles" array, but it is always empty.
It is not "undefined" but it is an empty array as i defined it in the constructor. its like the entries have never been set... but they are (as console.log() shows, when i insert it directly after the for()-loop)
console.log(this.handles); // --> []
Why does this happen?
this.handles is an array. So when you are doing this.handles[elmnt['id']], elmnt['id'] returns a string, whereas an array expects (positive) integer for index. So the elements are not set in the array.
Maybe you meant this.handles to be an object?
class Ex1 {
constructor() {
this.handles = {};
}
bla() {
let elmnts = document.querySelectorAll("p"); // 5x
for (let i = 0; i < elmnts.length; i++) {
let elmnt = elmnts[i];
this.handles[elmnt['id']] = elmnt; // saves the handles to each element in separate array for later use
}
}
}
class Ex2 extends Ex1 {
constructor(){
super();
}
m1(){
console.log(this.handles);
}
}
let p1 = new Ex2();
p1.m1();
p1.bla();
p1.m1();
<p id="one">1</p>
<p id="two">2</p>
<p id="three">3</p>
<p id="four">4</p>
<p id="five">5</p>
You need to understand the following things:
In Javascript...
arr.push(el).p element id as a key and assigning it the element reference). See this example:If you need an array (which preserves order and can easily be iterated later on), just spread the NodeList you got from querySelectorAll('p') into the array using the ES6 spread syntax ...:
this.handles = [...document.querySelectorAll("p")];