Friday, 17 July 2020

Get all hrefs as an array in jQuery

My code looks like this:

<ul id='ulList'>
  <li class='listClass' id='id1'><a href='http://link1'>Link 1</a></li>
  <li class='listClass' id='id2'><a href='http://link2'>Link 2</a></li>
  <li class='listClass' id='id3'><a href='http://link3'>Link 3</a></li>
</ul>

Now I like to get the following:

All links as an array

All ids of li as an array

Can someone help me please?


Answers:


This should work.

var ids = [],
    hrefs = []
;   
$('#ulList')
    .find('a[href]')  // only target <a>s which have a href attribute
        .each(function() {
            hrefs.push(this.href);
        })
    .end()
    .find('li[id]')   // only target <li>s which have an id attribute
        .each(function() {
            ids.push(this.id);
        })
;

// ids = ['id1', 'id2', 'id3']
// hrefs = ['http://link1', 'http://link2', 'http://link3']

Answers:


var ids = new Array();
var hrefs = new Array();
$('#ulList li').each(function(){
  ids.push($(this).attr('id'));
  hrefs.push($(this).find('a').attr('href'));
})

Answers:


var links = [], ids = [];
var $ul = $('#ulList');
var $lis = $ul.children('li');
var $as = $lis.children('a');

for(var count = $lis.length-1, i = count; i >= 0; i--){
    ids.push($lis[i].id);
    links.push($as[i].href);
}

Answers:


Stumbled into this question and came up with a more reusable answer:

$.fn.collect = function(fn) {
    var values = [];

    if (typeof fn == 'string') {
        var prop = fn;
        fn = function() { return this.attr(prop); };
    }

    $(this).each(function() {
        var val = fn.call($(this));
        values.push(val);
    });
    return values;
};

var ids = $('#ulList li').collect('id');
var links = $('#ulList a').collect('href');

You can also pass a function into collect like so:

var widths = $('#ulList li').collect(function() {
    return this.width();
});

Answers:


I know this is old, but as I like the oneliners that jQuery allows you to write, I thought I'd add it:

var allLinks = $('#ulList a').map(function(i,el) { return $(el).attr('href'); }).get();
var allIds = $('#ulList li').map(function(i,el) { return $(el).attr('id'); }).get();

Answers:


If you like one liners and hate having to instantiate an empty array.

[]
  .slice
  .call($('#ulList a'))
  .map(el => el.getAttribute('href'))

Answers:


Same code as provided by Grimace but in ES6

const allLinks = $('#ulList a').map((i,el) => $(el).attr('href')).get();
const allIds = $('#ulList li').map((i,el) => $(el).attr('id')).get();

Answers:


No comments:

Post a Comment