Skip to content
Advertisement

How to Use document.getElementById with Multiple IDs in JavaScript?

i want to change the code of both the button after clicking it work fine when I use single id but when I use multiple id it did not work I am still learning js so any idea will be helpfull

const btn = document.getElementById('copy_btn','down_btn');
copy_btn.addEventListener('click', function handleClick() {
  btn.innerHTML = `<iconify-icon icon="akar-icons:copy"></iconify-icon> Copied`;
});
down_btn.addEventListener('click', function handleClick() {
  btn.innerHTML = `<iconify-icon icon="ri:file-download-line"></iconify-icon> Downloading`;
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" 
        integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
    <!-- iconify cdn -->
    <script src="https://code.iconify.design/iconify-icon/1.0.0/iconify-icon.min.js"></script>
<button type="button" class="btn btn-dark" id="down_btn"><iconify-icon icon="ri:file-download-line"></iconify-icon> Download</button>
          <button type="button" class="btn btn-dark"   onclick="copyEvent();" id="copy_btn"><iconify-icon icon="akar-icons:copy"></iconify-icon> Copy </button>

Advertisement

Answer

Here’s an approach, define a function addClickHandlers which takes in an array of elements (each element has an id, icon and text) and then adds click handlers for each element.

const addClickHandlers = (ids) => {
  ids.forEach(({ id, icon, text }) => {
    const element = document.getElementById(id);
    element.addEventListener("click", function handleClick() {
      element.innerHTML = `<iconify-icon icon="${icon}"></iconify-icon> ${text}`;
    });
  });
};

addClickHandlers([
  { id: "copy_btn", icon: "akar-icons:copy", text: "Copied" },
  { id: "down_btn", icon: "ri:file-download-line", text: "Downloading" },
]);
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"><script src="https://code.iconify.design/iconify-icon/1.0.0/iconify-icon.min.js"></script><button type="button" class="btn btn-dark" id="down_btn"><iconify-icon icon="ri:file-download-line"></iconify-icon> Download</button><button type="button" class="btn btn-dark" onclick="copyEvent();" id="copy_btn"><iconify-icon icon="akar-icons:copy"></iconify-icon> Copy </button>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement