23

I want to iterate a result of query selector.

Html code

<nav id="navigation">
        <a href="#" tabindex="1" class="active_nav">nav1</a>
        <a href="#" tabindex="2">nav2</a>
        <a href="#"tabindex="3">nav3</a>
</nav>

when I use javascript

alert($("#navigation >a")[0]);

the result is the tag a href attribute I don't know why.

bohan
  • 1,659
  • 3
  • 17
  • 29

6 Answers6

34

Use $.each

$("#navigation > a").each(function() {

     console.log(this.href)
});

$('#navigation > a')[0]
      ^              ^---- Selects the 1st dom object from the jQuery object
      |                    that is nothing but the index of the element among 
      |                    the list of elements
      |-------  Gives you children of nav(3 anchor tags in this case)  which is a
                jQuery object that contains the list of matched elements
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • why the `$("#navigation >a")[0];` returns the href attribute of the first tag not the 1st dom object – bohan Jul 18 '13 at 09:28
3

You can use jQuery built-in each() for this iteration like this:

$("#navigation>a").each(function(index){
    console.log("I am " + index + "th element.");
    //and you can access this element by $(this)
});
frogatto
  • 28,539
  • 11
  • 83
  • 129
3

If you want to iterate all <a> tags, you can use each function

$('#navigation >a').each(function() { 
    alert(this.href);
});

and if you only want to get the first <a> tag then use .eq()

alert($('#navigation >a').eq(0).attr('href');
Setrákus Ra
  • 255
  • 1
  • 8
3

Use first() like this:

var element = $("#navigation>a").first();
console.log(element);

Reference

EpokK
  • 38,062
  • 9
  • 61
  • 69
  • but I want to iterate the whole set not only the first one. and I want to know why the `$("#navigation >a")[0];` returns the href attribute of the first tag. – bohan Jul 18 '13 at 09:15
  • 1
    Your query: "I want to get the first DOM object but not the attribute of the first object" – EpokK Jul 18 '13 at 10:29
2

In jQuery, when you use index like [0], it means you are access the DOM element. That is why

$("#navigation >a")[0]

returns <a> tag.

In order to iterate a jQuery selector result, use each

$("#navigation >a").each(function(index, elem){
});
U.P
  • 7,357
  • 7
  • 39
  • 61
-1

Try using

console.log($("#navigation >a"))

instead, so you can see all the results in the console ( cmd + alt + i in chrome)

Jonas Grumann
  • 10,438
  • 2
  • 22
  • 40