简体   繁体   中英

Get the href attribute for each link in a section of HTML

I've written the following jQuery to loop through each of the <a> objects in a section of HTML:

$(".chapterindex" + key + " div.link a").each(function(intIndex){
  alert("Numbered index: " + intIndex);
});
});

The key value used in the first line of the jQuery is from an array of URL's I've built manually, something like this:

var chapters = new Array();
chapters[0] = "original/html/0/ID0EFJAE.html";

I can alert the intIndex which gives me, 0,1,2,3,4,5.... etc..

But how can I extend the jQuery above to get the href attribute from each of the links found in the HTML?

Try this:

$(".chapterindex" + key + " div.link a").each(

    function(intIndex){
        alert( "Numbered index: " + intIndex );

        var href = $(this).attr('href');
    });
});

您可以通过$(this).attr('href')访问它

$(".chapterindex" + key + " div.link a").each(

    function(intIndex){
        alert( "Numbered index: " + $(this).attr("href") );
    });
});
$(".chapterindex" + key + " div.link a").each(function () {
  alert(this.href);
});

Do you want the full HREF or the HREF as it appears in the tag?

The jQuery object method $(this).attr('href') proposed by some people will return whatever is set as the HREF attribute in the tag.

The DOM node property method this.href proposed by John will return the fully-qualified URL.

So given a link <a href="/resources/foo.ext">Foo</a> , the jQuery method will return "/resources/foo.ext" while the other method will return "http://mysite.ca/currentpath/resources/foo.ext".

So it just depends on what you need returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM