SoulieBaby
SoulieBaby

Reputation: 5471

jquery to grab link and text based on class

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.

Upvotes: 0

Views: 405

Answers (3)

Jrubins
Jrubins

Reputation: 249

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

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630429

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 :)

Upvotes: 5

nickf
nickf

Reputation: 546055

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.

Upvotes: 2

Related Questions