Reputation: 2578
I have a javascript object with an event listener on a bunch of elements based on class name. Each one of these elements has an id, which I will use in other functions in my object. Right now, all I'm trying to do is get the id to print out in the console. I'm having trouble gaining access to these ids. My code is structured like below:
HTML
<div class="class-name" id="one" >Element 1</div>
<div class="class-name" id="two" >Element 2</div>
<div class="class-name" id="three">Element 3</div>
Javascript
window.onload = function() {
object.eListener();
}
var object = {
info : document.getElementsByClassName('class-name'),
eListener : function() {
var className = this.info;
for (var i = 0; i < className.length; i++) {
className[i].addEventListener('click', function() {
console.log(document.getElementsByClassName[i].id);
});
}
}
}
When the divs with the event listeners are clicked, console is logging undefined
. I've tried just logging the element without referencing the id, and replacing all of the className
variables with document.getElementByClassName
, but that did not seem to work either.
How do I print the ids of the elements with the class class-name
? Just to note in advance, I will not be using jQuery for this.
Upvotes: 1
Views: 2370
Reputation:
It's near to work,
console.log(this.id);
If you want to use i
in this scope you can create/execute a anonymous function passing i
as parameter.
for (var i = 0, len = className.length; i < len; i++) (function(i) {
className[i].addEventListener('click', function() {
console.log(className[i].id);
});
})(i);
Upvotes: 1
Reputation: 4261
The following should help:
HTML
<div class="class-name" id="one" >Element 1</div>
<div class="class-name" id="two" >Element 2</div>
<div class="class-name" id="three">Element 3</div>
JS
window.onload = function() {
object.eListener();
}
var object = {
info : document.getElementsByClassName('class-name'),
eListener : function() {
var className = this.info;
for (var i = 0; i < className.length; i++) {
className[i].addEventListener('click', function() {
console.log(this.id);
});
}
}
}
Example FIDDLE
Upvotes: 2
Reputation: 168
If the class name is always the same then this works
var info = document.getElementsByClassName('class-name');
for (i = 0; i <info.length; i++){
console.log(info[i].id);
}
Upvotes: 2