Towkir Towkir - 3 months ago 8
HTML Question

JavaScript - How do I get an element from an array after clicking on it

I have some divs like this:

<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<div id="four"></div>
<div id="five"></div>
<div id="six"></div>
<div id="seven"></div>


their (id)s are different but I have applied same classname on them,
So, I can now access them like this

var box = document.getElementsByClassName("clsname");


this created an array named box.
I want to write a JavaScript function that returns the clicked element in the array.
For example the function will be triggered when I click any of the box and will return the clicked box (div) element.

I want to do it with pure JS, no jquery please :)

Thanks

Answer

Here's an easy way to loop over them and add an event listener:

var testList = document.getElementsByClassName("clsname");

for(var i = 0; i < testList.length; i++) {
    testList[i].addEventListener('click', function() {
        console.log(this.id);
    });
}

Here's a JSBin with an example on it.

What the code does is loop through the NodeList, then add an event listener on click to log their ID. Here's a snippet:

var testList = document.getElementsByClassName("test");

for(var i = 0; i < testList.length; i++) {
    testList[i].addEventListener('click', function() {
        console.log(this.id);
    });
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
    <div id="one" class="test">1</div>
    <div id="two" class="test">2</div>
    <div id="three" class="test">3</div>
    <div id="four" class="test">4</div>
    <div id="five" class="test">5</div>
    <div id="six" class="test">6</div>
    <div id="seven" class="test">7</div>
</body>
</html>

If you want, you can use a forEach loop from Array like so:

var testList = document.getElementsByClassName("clsname");

Array.prototype.forEach.call(testList, function(element, index) {
    element.addEventListener('click', function() {
        console.log(this.id);
    });
});