How to set an attribute to each link that was clicked?

I have a webpage with this HTML:

<a href="">1</a>
<a href="">2</a>

I want that each link that was clicked (desirably, by the click() method) would start to include a data-clicked attribute-value directly after it was clicked for the first time.

Is there any way to do that?

Hi @bendqh1, yes calling click() on an element will fire a click event like a regular pointer action… so you can add event listeners like so:

const links = document.querySelectorAll('a')

links.forEach(link => {
  link.addEventListener('click', event => { = 'clicked'
  }, { once: true })

… and with the once option set to true, each event listener will remove itself after the first event it received.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.