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&category_id=6">AAAAA</a></li>
<li><a class="mainlevel" href="/index.php&category_id=10">BBBBB</a></li>
<li>&l开发者_如何学Ct;a class="sublevel" href="/index.php&category_id=11">CCCCC</a></li>
<li><a class="sublevel" href="/index.php&category_id=12">DDDDD</a></li>
<li><a class="mainlevel" href="/index.php&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&category_id=6">AAAAA</a>
<a class="mainlevel" href="/index.php&category_id=10">BBBBB</a>
<a class="mainlevel" href="/index.php&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.
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 :)
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.
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
精彩评论