My code looks like this:
- Link 1
<
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();
});
I came looking for a one-liner. Here's what I came up with:
var hs=[]; $('a').each(function(i,a){hs.push(a.href);}); hs;
If you like one liners and hate having to instantiate an empty array.
[]
.slice
.call($('#ulList a'))
.map(el => el.getAttribute('href'))
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();
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']
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);
}