How to get all the links of a list inside a div?

后端 未结 4 1233
天命终不由人
天命终不由人 2020-12-13 00:20

I have a code with the following DOM Tree:

4条回答
  •  执念已碎
    2020-12-13 01:03

    The function you are likely looking for is map. This allows you to take a given jQuery collection and transform it by taking a specific property of each object and making that the element in the resulting collection.

    To collect all the href's in your array:

    $(function() {
        var links = $("#blogPagination ul a").map(function() {
            return this.href;
        }).get();
        console.log(links);
    });
    

    jsFiddle Demo

    Note: The child selector (el1 > el2) only works when el2 is, well, a direct descendant of el1. So at least one of your examples would have failed because you didn't match that with your DOM tree. However, console.log($('#blogPagination div ul > li a ').attr("href")); would work to find the href of (only) the very first anchor tag, assuming you wrapped it in a DOM-ready handler $(function() { ... });.

    The children method is similar, in that it will only find direct descendants (children), and not grandchildren, etc. If you want to find all descendants down the DOM tree of a particular element, use find instead.

提交回复
热议问题