I am trying to create an array containing all the anchor links in a string. For example, if I have a string like the following
<a href=";Google</a>
<a href=";Google 2</a>
It should return me an array of two elements containing
My string is obtained from a textarea, so I tried
var html = $("textarea[name=html]").val();
var links = $(html).find('a').attr('href');
console.log(links);
However, only one link (presumably the first one in the string) is showing up. I know I might need to loop through all the anchors in the string, but how can I do it?
I am trying to create an array containing all the anchor links in a string. For example, if I have a string like the following
<a href="http://google.it>Google</a>
<a href="http://google.>Google 2</a>
It should return me an array of two elements containing
http://google.it
http://google.
My string is obtained from a textarea, so I tried
var html = $("textarea[name=html]").val();
var links = $(html).find('a').attr('href');
console.log(links);
However, only one link (presumably the first one in the string) is showing up. I know I might need to loop through all the anchors in the string, but how can I do it?
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Oct 25, 2016 at 15:52 wiredmarkwiredmark 1,1087 gold badges26 silver badges45 bronze badges 02 Answers
Reset to default 4attr()
only returns the first match, you have to map the attributes back
var arr = $('<div />', {html:html}).find('a').map(function() {
return $(this).attr('href');
}).get()
var str = arr.join(','); // if you need a string
.attr()
will return just the first element attribute try to iterate all the elements and store the attribute in array :
var links = [];
$('body').find('a').each(function(){
links.push( $(this).attr('href') );
})
console.log(links);
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://google.it">Google</a>
<a href="http://google.">Google 2</a>