I need to retrieve all the hyperlinks present in current html page using jquery. How can i use regular expressions to do that? Also can i use collections in javascript to store all the hrefs in the list?
6 Answers
You can use simple each-loop:
// For each <a href=""> tag...
$('a').each(function(){
// Get the url
var href = $(this).attr('href')
// alert it or do sth with it
alert( href );
})
3 Comments
$(html_tring_here).find('a').each(....filter() rather than .find() because .find() won't match any top-level elements.using jQuery $('a') will do it for you
Iterating through all the anchor elements
var hrefArr = [];
$('a').each(function(){
//hrefArr.push($(this).attr('href'));
hrefArr.push(this.href); // this would be bit faster then the statement above it
});
Edit on comment by OP, Finding the anchor tags in string contain html
str = "<div><a href='local1'></a><a href='local2'></a></div>"
var hrefArr = [];
$(str).filter('a').each(function(){
hrefArr.push(this.href);
});
4 Comments
.filter() rather than .find() because .find() won't match any top-level elements in the string. (Your example string would of course work with .find() since you assumed a div as a container.)All anchors would be quite easy
$("a").each(function(){
alert( $(this).attr("href") );
})
1 Comment
This will give you all the hyperlinks on the page
$('a')
And this will give you collection of hrefs on the hpyerlinks
var hrefs = new Array();
$('a').each(function() {
hrefs.push(this.attr('href'));
});
2 Comments
href attribute of the first anchor tag, not a collection.If by "collections in javascript" you mean an array then you can do this:
var hrefs = [];
$("a").each(function() {
hrefs.push(this.href);
});
// hrefs array now contains all the hrefs
Within the .each() callback function this.href will likely return the full url that would be followed if you click the link, that is href="test.htm" would be returned as http://yourdomain/test.htm. If you want just the bit literally in the attribute use $(this).attr("href").
You wouldn't use a regex to do that type of processing.
2 Comments
str then you could do $(str).filter("a").each(...Try this:
var link = "";
$("a").each(function() {
link += $(this).attr("href");
});
alert(link);