I am trying to console.log the value of data-number attribute of <span>
on click event using JavaScript. Multiple spans are dynamically created during the execution of the code on the client side and each of them have a class "dynamic-span".
Sample:
<span class="dynamic-span" data-number="1">This is a dynamic span</span>
So when the above span is clicked, number "1" will be console logged.
I am able to log the number using jQuery.
$("body").on("click", ".dynamic-span", function (e) {
e.preventDefault();
var number = $(this).data("number");
console.log(number);
});
I want to achieve the same result using plain JavaScript.
I am targeting the span using the "dynamic-span" class.
var elems = document.getElementsByClassName("dynamic-span");
So, I am able to get the spans using the ClassName. But I am getting HTMLCollection and not an Array and the for loop is not working.
Code:
var
elems = document.getElementsByClassName("dynamic-span"),
i;
for (i = 0; i < elems.length; i++) {
elems[i].addEventListener("click", function (e) {
console.log(this.getAttribute("data-number"));
});
}
I have also checked the following StackOverflow question JavaScript click event listener on class but no success.
The following reference https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName suggests the Element.getElementsByClassName() method returns a live HTMLCollection.
Kindly suggest a way to accomplish the above task.