Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to iterate a result of jquery selector

Tags:

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.

like image 743
bohan Avatar asked Jul 18 '13 07:07

bohan


Video Answer


2 Answers

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 
like image 109
Sushanth -- Avatar answered Sep 18 '22 15:09

Sushanth --


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'); 
like image 36
Setrákus Ra Avatar answered Sep 20 '22 15:09

Setrákus Ra