Dev Notes

Software Development Resources by David Egan.

Attach Click Event to Many Elements in Javascript


JavaScript
David Egan

Plain JavaScript: loop through elements by class name and attach a click event using Array.forEach.

The getElementsByClassName() method returns a HTMLCollection object. This needs to be converted to an array before iterating with Array.forEach():

const view = {
  display: function() {
    const address = controller.getAddress()
    let displayAddress = `
    <table>
    <tr><td>Address:</td><td class="selector" title="Double click to select">${address.address}</td></tr>
    <tr><td>Secret: </td><td class="selector" title="Double click to select">${address.secret}</td></tr>
    <tr><td>Public Key: </td><td class="form-selector">${address.publicKey}</td></tr>
    <tr><td>Private Key: </td><td>${address.privateKey}</td></tr>
    </table>
    `
    this.displayAddress.innerHTML = displayAddress
    // The forEach method requires an array, rather than a HTML collection
    const selectors = [].slice.call(document.getElementsByClassName('selector'))
    selectors.forEach((element, index) => {
      element.addEventListener('click', (event) => {
        // Send the text content of the clicked element for processing
        controller.copyToClipboard(event.target.textContent)
      })
    })
  }
}
// Prompt user to copy text to clipboard
const controller = {
  copyToClipboard: (text) => {
    window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
  }
}

comments powered by Disqus