Reputation: 93
I have some span in my DOM that have the class="foo" and all the spans are created dynamically.
With TypeScript i want to add an onClick Event to all of them after their creation.
I have something like this :
var foos = document.body.querySelectorAll(".foo");
foos.forEach(function (item) {
item.addEventListener("click", () => {
console.log(item);
});
});
But i can't do forEach on a NodeListOf.
foos = Array.from(foos) does not work because : 'from' doesn't exist on type 'ArrayConstructor'.
Upvotes: 0
Views: 487
Reputation: 6516
I made three different approaches that you can use, they are very simple, please open each code snippet to see it working.
1 - This Example shows how to add the listener AFTER the creation of elements.
for (var i = 0; i < 4; i++){
var a = document.createElement('input');
a.type = 'button';
a.value = 'click me ' + i;
a.className = 'foo';
document.body.append(a);
}
//JQUERY WAY
$('.foo').on('click', function(){
console.log(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
2 - This Example shows how to add the listener BEFORE the creation of elements.
//JQUERY WAY
$(document).on('click', '.foo', function(){
console.log(this.value);
});
for (var i = 0; i < 4; i++){
var a = document.createElement('input');
a.type = 'button';
a.value = 'click me ' + i;
a.className = 'foo';
document.body.append(a);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
3 - And finally, if don't want jQuery, here's a Vanilla JS example:
for (var i = 0; i < 4; i++){
var a = document.createElement('input');
a.type = 'button';
a.value = 'click me ' + i;
a.className = 'foo';
document.body.append(a);
}
//VANILLA JS WAY
var myElems = document.querySelectorAll('.foo');
myElems.forEach(function(elem){
elem.onclick = function(){
console.log(elem.value);
}
});
Upvotes: 1
Reputation: 2618
Since you tagged your question with jquery
, here's the jquery
way:
$(".foo").click( function() {
// Do something here
});
Upvotes: 3
Reputation: 30739
Use simple for
loop for this. You can get elements for each index in the foos
array and assign click event on them. This is because querySelectorAll
returns a NodeList
which is indexed like an array, but not an Array so you can't call the array methods on it as it is not a real array.
var foos = document.body.querySelectorAll(".foo"));
for(var i=0; i<foos.length; i++){
foos[i].addEventListener("click", () => {
console.log(item);
});
});
Upvotes: 3