Question

I have the below HTML code

<a href="http://www.google.com">Google</a>

When I click on the link, I want my string to contains the full HTML code below

<a href="http://www.google.com">Google</a>

I tried using this method, but I only manage to get the text "Google", can't get the anchor code.

$('#frame').contents().find('body').on("click", "a",  function () {
    var string = $(this).html();
    alert(string);
});

String alert only Google when I need <a href="http://www.google.com">Google</a>.

Was it helpful?

Solution

Use this.outerHTML, or wrap the element in a container, and use .html() on that container.

$('#frame').contents().find('body').on("click", "a",  function () {
    var string = this.outerHTML;
    alert(string);
});

I prefer outerHTML, but Firefox has only recently added support for it. So, to account for these browsers, the second method might be preferred.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top