user8008522
user8008522

Reputation:

Set onclick event to a class of elements: how to get id of the one clicked? javascript only

The problem:

I have 134 elements which must have an onclick event attached. I am doing this by now, on eeeeeeevery single one of them (and they have an ondbclick event attached too!):

<div id="id1" class="name" onclick="functionName(this.id)"></div>
<div id="id2" class="name" onclick="functionName(this.id)"></div>
<div id="id3" class="name" onclick="functionName(this.id)"></div>

but read in Eloquent Javascript (chapter 14) that this is considered bad practice, since it mixes html and javascript.

So I thought I could find a way to attach the onclick event to all of them together. I searched a few hours and tried a few things, like this: (from 'How do you set a JavaScript onclick event to a class with css' here on stackoverflow)

window.onload = function() {
    var elements = document.getElementsByClassName('nameOfTheClass');
    for(var i = 0; i < elements.length; i++) {
        var OneElement = elements[i];
        OneElement.onclick = function() {
           //do something
        }
    }
}

Which got the click to work on the elements, but not my function.

My original function was receiving two values, the id and the innerHTML of the element that got clicked, and now I cannot find a way to access that information.

I tried OneElement.id and OneElement.innerHTML just to find out that it gets the id and innerHTML of the last of the elements in the document.

Any clues? Any help very much appreciated! :)

Upvotes: 1

Views: 4177

Answers (3)

Govind Rai
Govind Rai

Reputation: 15800

When an event is triggered in JavaScript, it passes an event object to the callback function. Pass that into the signature and you will gain access to element's properties.

window.onload = function() {
    const elements = document.getElementsByClassName('nameOfTheClass');
    
    for (const element of elements) {
        element.addEventListener("click", e => {
            console.log("element was clicked", e.target.id, e.target.innerHTML);
        })
    }
}

Upvotes: 7

Rico Kahler
Rico Kahler

Reputation: 19222

There are two DOM apis I would recommend you use:

  1. document.querySelector and document.querySelectorAll and
  2. element.addEventListener('click', event => {/* ... */});

Those are my gotos for "vanilla js" dom manipulation.

See the example below for what you wanted.

Array.from(document.querySelectorAll('.name')).forEach(element => {
  // for each element that matches the querySelector `.name`
  element.addEventListener('click', clickEvent => {
    // call your function when the element is clicked
    // see the properties of a Dom Element here:
    // https://developer.mozilla.org/en-US/docs/Web/API/Element
    yourFunction(element.id, element.innerHTML);
  });
})

function yourFunction(id, innerHtml) {
  // use the values!
  console.log({id, innerHtml});
}
<div id="id1" class="name">[click me] inner html 1</div>
<div id="id2" class="name">[click me] inner html 2</div>
<div id="id3" class="name">[click me] inner html 3</div>

Upvotes: 0

Dmitry Druganov
Dmitry Druganov

Reputation: 2358

<div id="id1" class="name">first</div>
<div id="id2" class="name">second</div>
<div id="id3" class="name">third</div>
<script type="text/javascript">
  var nodes = document.querySelectorAll('.name');
  Array.from(nodes).forEach(function (node) {
    node.addEventListener('click', function (event) {
      alert('you clicked' + event.target.textContent + ' with id: ' + event.target.getAttribute('id'));
      // you might also use event.target.innerHTML here
    });
  });
</script>

Upvotes: 0

Related Questions