Skip to content

“href” parameter only onmouseover

I have following problem. I have pre-defined href on link which I can’t change or remove in html. I need to have this href only onmouseover. So I removed it with:


Now I need to add this href back but only onmouseover, so in default there will be no href attribute and onmouseover will enable it. But this and similar solutions doesn’t work:

document.getElementsByClassName("class")[0].onmouseover="this.href = 'urlHere';"

Is there any way how to do this?



As I mentioned in my comment, you almost certainly shouldn’t do this, because it will break accessibility. If you just want to change some styling, use CSS and the :hover pseudo-class selector.

However, if you really did have a legitimate use case for this, the best way to do it would be using a WeakMap:

const links = document.querySelectorAll('.link-class-name')

const map = new WeakMap()

links.forEach(link => {
    map.set(link, link.href)


    link.addEventListener('mouseenter', () => link.href = map.get(link))
    link.addEventListener('mouseleave', () => link.removeAttribute('href'))

WeakMaps are cool because they allow you to store arbitrary metadata about arbitrary objects in a way that can be garbage collected when it’s no longer needed. This makes them perfect for storing and retrieving data about DOM nodes.

User contributions licensed under: CC BY-SA
6 People found this is helpful