Populating a javascript array with links of a specific class

I want to take a website source and populate an array with a collection of links filtered by them a class

.

Let's say for example what the links were <a class="title">

, how could I target each class and add the url to the array?

Will Javascript or jQuery work better?

+3


source to share


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


It's pretty easy with jQuery:



var arr = [];
var ptr = 0;

$('.title').each(function() {
    arr[ptr] = $(this).attr('href');
    ptr++;
}) 

      

0


source


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


With jQuery, you can do var urls = $("a.title").attr("href")

to get what you want.

0


source


You can do something like below,

var linkURL = [];
$('a.title').each (function () {
   linkURL.push(this.href);
});

      

0


source







All Articles