最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting all anchors from a string in jQuery - Stack Overflow

programmeradmin3浏览0评论

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 0
Add a ment  | 

2 Answers 2

Reset to default 4

attr() 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>

发布评论

评论列表(0)

  1. 暂无评论