jQuery: 获取链接的html码

jQuery: Get html code of links

我想在不使用正则表达式的情况下从 div 获取 html 链接。

例如:

<div>Please check your links to ensure they point to the correct article.For example, <a href="http://en.wikipedia.org/wiki/Apple">Apple</a> points to the article about the fruit, while <a href="http://en.wikipedia.org/wiki/Apple_Inc.">Apple Inc.</a> is the title of the article about the consumer electronics manufacturer. </div>

我只想抄写

HTML:

<a href="http://en.wikipedia.org/wiki/Apple">Apple</a> and <a href="http://en.wikipedia.org/wiki/Apple_Inc.">Apple Inc.</a>


我尝试使用:

$('div a').each(function () {
     $(this).html();
});

但这不起作用。

您可以使用 outerHTML 属性 映射它,然后 join 数组:

var html = $('div').children('a').map(function(){
    return this.outerHTML;
}).get().join(' and ');

-jsFiddle-

要专门处理多个 DIV,您可以使用:

$('div:has(a)').each(function () {
    this.innerHTML = $(this).children('a').map(function () {
        return this.outerHTML;
    }).get().join(' and ')
});

-jsFiddle-