bohan
bohan

Reputation: 1699

how to iterate a result of jquery selector

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.

Upvotes: 26

Views: 31558

Answers (6)

Sushanth --
Sushanth --

Reputation: 55740

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

Upvotes: 39

EpokK
EpokK

Reputation: 38092

Use first() like this:

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

Reference

Upvotes: 3

Setr&#225;kus Ra
Setr&#225;kus Ra

Reputation: 255

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');

Upvotes: 3

frogatto
frogatto

Reputation: 29285

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)
});

Upvotes: 3

U.P
U.P

Reputation: 7442

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){
});

Upvotes: 2

Jonas Grumann
Jonas Grumann

Reputation: 10786

Try using

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

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

Upvotes: -1

Related Questions