Search code examples
javascriptanchorhrefonmouseoverqueryselector

Attach onmouseover function() to all hrefs and srcs in page to access them?


I want to access href and src links via simply attaching onmouseover = function to them. Here is my attempted codes:

HTML

<p><a href="https://dannychoo.com/en/instagram/p/BYnMQSpBcmY">Lass</a></p>
<a href="https://developer.mozilla.org">interest</a>
<p><a src="https://mirai-instagram-images.s3.ap-northeast-1.amazonaws.com/dannychoo/17897602822049811/21296657_120344735358000_817812329218441216_n.jpg">stuff</img></p>

Javascript:

document.querySelectorAll("a").onmouseover = function() {
let g, i; 
g = document.querySelectorAll("a").getAttribute("href")
for (i = 0; i < g.length; i++) {
location.assign(g[i]);
      }
 } 

Thanks for your helpful answers.


Solution

  • Assuming you want to get these attributes regardless of tag type, you can query multiple selectors with querySelectorAll. You can also loop through the results with forEach.

    You can target elements by attribute with CSS, you can read more about that here.

    Modern browsers support looping through querySelectorAll results, but if you need old browser support check out this article for alternatives

    var links = document.querySelectorAll("[src], [href]");
    links.forEach(link => {
      link.addEventListener("mouseover", e => {
        const href = e.target.href;
        const src = e.target.getAttribute("src");
        if (src) console.log(src);
        if (href) console.log(href);
      });
    });
    <p><a href="https://dannychoo.com/en/instagram/p/BYnMQSpBcmY">Lass</a></p>
    <a href="https://developer.mozilla.org">interest</a>
    <p><img src="https://mirai-instagram-images.s3.ap-northeast-1.amazonaws.com/dannychoo/17897602822049811/21296657_120344735358000_817812329218441216_n.jpg">stuff</p>

    Fiddle