jQuery HTML Element How to - Loop through all anchors on a page








Question

We would like to know how to loop through all anchors on a page.

Answer


<html>
<script>
        function explode() {<!--   ww w  .ja  v a 2s . c o  m-->
                pp = document.getElementsByTagName("a");
                var a='';
                for(i=0;i<pp.length;i++) {
                  a+=pp[i].href
                }
                document.write(a);
        }
</script>
<body>
  <a href="http://google.com">Google</a>
  <a href="http://yahoo.com">Yahoo</a>
  <button onclick="explode()">Explode</button>
<body>
</html>

The code above is rendered as follows: