Populating a javascript array with links of a specific class
5 answers
var arr = new Array();
$("a.title").each(function()
{
arr.push($(this).attr("href"));
});
So, basically you create an array using the Array constructor . Then you use JQuery each to iterate over links with a class title
, getting your urls using attr and pushing them into an array along the path.
+3
source to share
Something like
var collectionOfLinks = {};
$('a').each(function() {
var cl = $(this).attr('class');
if (collectionOfLinks[cl] === undefined) {
collectionOfLinks[cl] = [];
collectionOfLinks[cl].push($(this).attr('href'));
}else{
collectionOfLinks[cl].push($(this).attr('href'));
}
});
This gives you an object whose property names are element classes <a>
and whose values are href arrays
0
source to share