Get all hrefs as an array in jQuery

后端 未结 8 1298
[愿得一人]
[愿得一人] 2020-12-17 20:41

My code looks like this:

  • Link 1
  • <
相关标签:
8条回答
  • 2020-12-17 20:41

    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();
    });
    
    0 讨论(0)
  • 2020-12-17 20:41

    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;

    0 讨论(0)
  • 2020-12-17 20:42

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

    []
      .slice
      .call($('#ulList a'))
      .map(el => el.getAttribute('href'))
    
    0 讨论(0)
  • 2020-12-17 20:49

    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();
    
    0 讨论(0)
  • 2020-12-17 20:53

    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']
    
    0 讨论(0)
  • 2020-12-17 20:58
    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);
    }
    
    0 讨论(0)
提交回复
热议问题