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

$('#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?


The Vanilla Javascript Solution

document.querySelectorAll("div #blogPagination a").forEach((item)=>console.log(item.href));

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.

Tags:

Html

Dom

Jquery