-5

I need to get all the links in the page using .each(function(){}); in JQuery

<div id="mm">
    <ul class="mg">
        <li id="nav_sports">
            <a href="http://www.google.com" class="atest">Sports</a>
            <div id="sports">
                <ul>
                    <li>
                        <a href="http://www.dictionay.com">cricket</a>
                    </li>
                </ul>
                <ul id="cont1">
                    <li style="color:#444444">
                        <b>Popular</b>
                    </li>
                </ul>
            </div>
        </li>
    </ul>
</div>
Kjuly
  • 34,476
  • 22
  • 104
  • 118
Debjeet Das
  • 151
  • 1
  • 3
  • 12

6 Answers6

19
$("a").each(function() {
    //Do your work   
})
Eli
  • 14,779
  • 5
  • 59
  • 77
6

Use the anchor tag as selector

$("a").each(....)
bart s
  • 5,068
  • 1
  • 34
  • 55
6
var links = [];
$('#mm a').each(function() {
   links.push( this.href ); 
   // output of links: ['http://www.google.com', 'http://www.dictionay.com']
   // According to comment
   // if you need each link separately then
   // may try like

   var href = this.href;
   // now process with the href as you wish      
});

for all as, change the selector #mm a to just a;

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
4

this is what i expected guys...thanks for ur replies

$("a").attr("clink","");
    $(window).load(function(){
        $("#mm a").attr("clink","");
        $('#mm a').each(function(){
            var hrefl=$(this).attr('href');
            var clink=hrefl;
            $(this).attr('clink',clink);
            $(this).attr('href',"#");
        }); 
});
Debjeet Das
  • 151
  • 1
  • 3
  • 12
4

If you want all the unique links on a page, borrowing from other answers on this page and Unique values in an array

function onlyUnique(value, index, self)
{
    return self.indexOf(value) === index;
} 

function getAllLinks()
{
   var links = [];
   $("a").each(function ()
   {
      links.push(this.href);
   });

   return links.filter(onlyUnique);
}
Community
  • 1
  • 1
Aaron Sherman
  • 3,789
  • 1
  • 30
  • 33
2

You can just do $('a') this will return a collection of al the A elements on a page.

Then you can iterate over it with $('a').each(function(index, value){})

Preben Huybrechts
  • 5,853
  • 2
  • 27
  • 63