if I use jquery it's working.
$(document).ready(function() {
$('btn').click(function() {
alert('start');
});
});
but I want use native es6
window.onload = function() {
let btn = document.getElementsByClassName( 'btn' );
for (let i of btn.length) {
i.onclick( function () {
alert( 'start' );
});
}
};
error btn.length[Symbol.iterator] is not a function
And this doesn't work too.
window.onload = function() {
let btn = document.getElementsByClassName( 'btn' );
for (let i=0; i < btn.length; i++) {
i.onclick = function () {
alert( 'start' );
};
}
};
if I use jquery it's working.
$(document).ready(function() {
$('btn').click(function() {
alert('start');
});
});
but I want use native es6
window.onload = function() {
let btn = document.getElementsByClassName( 'btn' );
for (let i of btn.length) {
i.onclick( function () {
alert( 'start' );
});
}
};
error btn.length[Symbol.iterator] is not a function
And this doesn't work too.
window.onload = function() {
let btn = document.getElementsByClassName( 'btn' );
for (let i=0; i < btn.length; i++) {
i.onclick = function () {
alert( 'start' );
};
}
};
Share
Improve this question
asked Jul 8, 2017 at 22:23
Atm54_17Atm54_17
1793 silver badges8 bronze badges
2
-
2
Second one should be
btn[i].onclick=...
noti.onclick
..i
is a number not an element – charlietfl Commented Jul 8, 2017 at 22:29 -
1
for... of
iterates a collection - sofor(let btn of buttons) { ...
and notof buttons.length
– Benjamin Gruenbaum Commented Jul 8, 2017 at 22:35
1 Answer
Reset to default 6The for of
loop will iterate over the elements of a collection that has a [Symbol.iterator]
property. In your ES6 snippet you are trying to iterate over the returned HTMLCollection length eg. for (let i of btn.length)...
.
Here is what you should do instead.
let btns = document.getElementsByClassName( 'btn' );
for ( let btn of btns ) {
btn.onclick = function() {
console.clear()
console.log(this.textContent)
}
}
<button class="btn">Btn 1</button>
<button class="btn">Btn 2</button>
<button class="btn">Btn 3</button>
<button class="btn">Btn 4</button>