aCarella aCarella - 3 months ago 6
HTML Question

How to reference an element's id based on looping through elements by class name

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.

Answer

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

Comments