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