Search code examples
javascriptgetelementbyiddisable-link

Disabling a link using getElementById where there are many links that could be clicked


document.getElementById("img1").addEventListener("click", function(event){
  event.preventDefault()
});

I have tried the above JavaScript, which does disable the link, while retaining right and middle button click actions which is what I want.

However, I have many links, each with a dynamically created ID and I cannot figure out how to pass the ID to the above code.

I have tried the following:

HTML:

<a id="img' . $row["idImage"] . '" onClick="passID(this.id)" href="images/img01"><div></div></a>

JavaScript:

function passID(linkId) {
  var imgid = linkId;
  alert(imgid);
  document.getElementById(imgid).addEventListener("click", function(event) {
    event.preventDefault()
  });

But it doesn't disable the link. I put an alert in and it does return the correct ID of the clicked link but does not disable it so I'm at a bit of a loss on how to proceed from here.


Solution

  • If you're okay with using event handler attributes, simply use onclick="return false;" and you're done.

    <a href="https://www.google.com/" onclick="return false;">Clicking me wont redirect.</a>

    If you want to use addEventListener(), then you'll need to be able to distinguish the elements that should not be able to redirect. You can use a selector like a[id^="img"] to select all anchor elements who's id attribute starts with img.
    Then you need to select all elements that apply, loop over them, and add the event listener.

    document.querySelectorAll('a[id^="img"]').forEach(anchorElement => {
      anchorElement.addEventListener('click', event => event.preventDefault());
    });
    <a href="https://www.google.com/" id="img1">Link 1</a>
    <a href="https://www.google.com/" id="img2">Link 2</a>

    Although it would probably be more clean and less error prone to add classes to your anchor tags that you want to prevent from redirecting and select those.

    document.querySelectorAll('.dont-redirect').forEach(anchorElement => {
      anchorElement.addEventListener('click', event => event.preventDefault());
    });
    <a href="https://www.google.com/" class="dont-redirect">Link 1</a>
    <a href="https://www.google.com/" class="dont-redirect">Link 2</a>