Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

jquery

dom

I have a code with the following DOM Tree:

<div id="blogPagination">     <div class="pagination">         <ul>             <li>                 <a href="/2" >1</a>             </li>             <li>                 <a href="/3" >2</a>             </li>         </ul>     </div> </div> 

I'm trying to reach the href of my tag. I can't reach it with anything I tried.

What's the best way to reach it with jQuery ?

I tried:

console.log($('#blogPagination div ul > li a ').attr("href"));

console.log($('#blogPagination > a ').attr("href"));

$('#blogPagination').children('a')

console.log($('#blogPagination div ul li a').attr("href"));

without luck ..

Thanks

EDIT:

After nbrooks's answer, here is what I tried so far:

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

EDIT 2 :

Considering Syfaro's answer, I've also tried :

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

Without luck.

EDIT 3 : I'd like to give more details concerning this function that may have a significant impact after all:

to load this pagination, I'm using Ajax and handlebars wrapped into a document ready function:

$(document).ready(function(){          // Get the customer service stats     var Content = {      init: function() {              /* this.getHomePosts(); */             this.getBlogPosts();         },      getBlogPosts: function(offset) {         if(offset == undefined){             offset = 0;         }         // GET the events with JSON         $.ajax({             type: "POST",             data: {},             url: site_url+"/main/blog/"+offset,             dataType: "json",             success: function(results) {                 posts = results["posts"].map(function (blogContent) {                     if( blogContent.picture != '' ) {                         return {                             Title: blogContent.title ,                             Picture: Content.urlPostPic + blogContent.picture ,                             Video: '' ,                             Text: blogContent.text ,                             Datetime: blogContent.datetime ,                         }                     } else {                         return {                             Title: blogContent.title ,                             Picture: '' ,                             Video: blogContent.video ,                             Text: blogContent.text ,                             Datetime: blogContent.datetime ,                         }                     }                 });                  pagination = {pagination: results["pagination"]};                  var template = Handlebars.compile( $('#templateBlog').html() );                 $('#blogPosts').append( template(posts) );                  var template = Handlebars.compile( $('#templatePagi').html() );                 $('#blogPagination').append( template(pagination) );                                     // Here we call bindPagination <===                 bindPagination();             }         });     },  };  Content.init(); 

You can see in the get BlogPosts function that I call BindPagination which is supposed to be this function, to prevent default behavior and call the content depending of the offset (pagination system)

function bindPagination() {          console.log("bind");           var links = $("#blogPagination ul a").map(function(e) {         e.preventDefault();         return this.href;     }).get();     console.log(links);      $('#blogPagination').find('a').each(function(e) {         console.log("clicked !");         e.preventDefault();         console.log($(this).attr('href'));       //    var attr = this.attr();         // var id = attr.replace("/","");          // $('#blogPosts').empty();         // $('#blogPagination').empty();         // Content.getBlogPosts(id);     }); } }); 

the last }); stand for the end of the document ready.

like image 319
Miles M. Avatar asked Aug 11 '13 18:08

Miles M.


People also ask

How do I turn an entire div into a link?

You can't make the div a link itself, but you can make an <a> tag act as a block , the same behaviour a <div> has. You can then set the width and height on it. However, this doesn't make a 'div' into a link. It makes a link into a block element.

Can an entire div be a link?

Sometimes, a design called for an entire <div> (or any other sectional element) to be a clickable link. A typical example is an entire block with some text and an image to be clickable from all around. Another example is an entire block that contains a link to an article: This is a block from my /blog page.

How do you create a list of links in Javascript?

Create a text node with some text which will display as a link. Append the text node to the anchor <a> element. Set the title and href property of the <a> element. Append <a> element in the body.

How do I find my anchor tag?

To find anchor tag in div, use a selector and the addClass() method adds a class using jQuery.


2 Answers

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

like image 86
ixchi Avatar answered Sep 21 '22 20:09

ixchi


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.

like image 35
nbrooks Avatar answered Sep 17 '22 20:09

nbrooks