views:

87

answers:

3

Hi all,

I'm trying to use jquery to grab the entire link depending on it's class.

Here's my code:

<ul class="vm_catTigra">
  <li><a class="mainlevel" href="/index.php&amp;category_id=6">AAAAA</a></li>
  <li><a class="mainlevel" href="/index.php&amp;category_id=10">BBBBB</a></li>
  <li><a class="sublevel" href="/index.php&amp;category_id=11">CCCCC</a></li>
  <li><a class="sublevel" href="/index.php&amp;category_id=12">DDDDD</a></li>
  <li><a class="mainlevel" href="/index.php&amp;category_id=13">EEEEE</a></li>
</ul>

Here's what I want jquery to grab for me (in an array):

<a class="mainlevel" href="/index.php&amp;category_id=6">AAAAA</a>
<a class="mainlevel" href="/index.php&amp;category_id=10">BBBBB</a>
<a class="mainlevel" href="/index.php&amp;category_id=13">EEEEE</a>

I have tried using this:

var mainlevel = [];
jQuery(".mainlevel").each(function() { 
  mainlevel.push(jQuery(this).html());
});

But it is returing AAAAA, BBBBB, EEEEE instead of the full line of code that I'm after.

+2  A: 

Like this:

$('a.mainlevel')

Or if there are more of those on the page and you only want the ones in that list:

$('.vm_catTigra a.mainlevel')

You should have a read of the documentation.

nickf
Sorry, I need it in an array
SoulieBaby
it is an array. $('a.mainlevel') returns an array of length 3 with all 3 anchor elements in it. you can test it out by placing a watch on $('a.mainlevel')[0], $('a.mainlevel')[1], $('a.mainlevel')[2]
John Hartsock
@John - If I understand correctly, she wants the html string of the entire link, so a 1x3 array of strings, not elements....I could be wrong though.
Nick Craver
+5  A: 

You can do it using .map() and .html() like this:

var linkArray = $("a.mainlevel").map(function() {
    return $(this).parent().html();
}).get()​​​​​​;

You can view a working demo here, the .get() on the end makes it so you get the native array object at the end...this will result in a 3 string array like your question :)

Nick Craver
that's what I'm after! thank you muchly :)
SoulieBaby
+1 and also Jsfiddle looks better than Jsbin, so thanks!
alex
A: 

you can iterate in each li and get the innerhtml then store them on an array like this.

var arr = ""; 
var arr_i = 0;
$(".mainlevel parent").each(function(){
  arr[arr_i] = $(this).html();
  arr_i++;
});

hope this helps

Jrubins
This isn't valid JavaScript syntax, or jQuery :)
Nick Craver
aha.. sorry.. forgotten the quotes
Jrubins
@Jrubins - Your `arr` is a string, not an array, also the `.each()` closure function already gets an index, it's the first parameter passed to the function, you could reduces to this: `var arr = []; $(".mainlevel").each(function(i){ arr[i] = $(this).html(); });`, but `parent` isn't a valid selector (that would look for `<parent>` elements inside the anchors), you need to access the parent in the loop, you can see my answer for how to do this.
Nick Craver