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

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

I have a code with the following DOM Tree:

相关标签:
4条回答
  • 2020-12-13 01:00

    Check your console - as I suspect there is either a conflict or javascript error that is causing the jQuery not to work.

    Your statements are correct and should select the element you require.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-13 01:22

    The Vannila Javascript Solution

    Array.prototype.map.call(document.querySelectorAll(".myselectorAreaofLinks"), function (e) {
      return e.getAttribute('href');
    });
    
    0 讨论(0)
  • 2020-12-13 01:23
    $('#blogPagination').find('a').attr('href');
    

    This should find all a elements in the specified area, the get the href of them, assuming that you've already got jQuery and all that good stuff set up.

    If you have multiple a elements, you could do something like this:

    $('#blogPagination').find('a').each(function() {
        console.log($(this).attr('href'));
    });
    

    This will print out each href of each a in that div.

    If you need to prevent the link from changing the page, you need to add a click handler to the a elements.

    $('#blogPagination').on('click', 'a', function(e) {
        e.preventDefault();
        console.log($(this).attr('href'));
    });
    

    This will prevent the user from being taken to the link, and get the href of the link when clicked.

    Is this what you want?

    0 讨论(0)
提交回复
热议问题