Notification texts go here Contact Us Buy Now!

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

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);
        })
    }
}
<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>
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});
}

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.