0

I want to get html links from a div without using regex.

For example:

<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>

I only want to copy and write.

HTML:

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


I tried using:
$('div a').each(function () {
     $(this).html();
});

but this doesn't work.

Mohsen Movahed
  • 418
  • 5
  • 22

1 Answers1

3

You could map it using outerHTML property and then join the array:

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

-jsFiddle-

For handling multiple DIVs specifically, you could use:

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

-jsFiddle-

A. Wolff
  • 74,033
  • 9
  • 94
  • 155