Using jQuery to Click on an Element and return it’s HTML

I was recently searching for a plug-in that returns the HTML for an element. I came across a solution suggested by Keegan that shows how to do so. Here’s the solution to find out the HTML of an element by clicking on it

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Make an Image Clickable</title>
<
script type='text/javascript'
src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'>
</
script>

<
script type="text/javascript">
$(function() {
$(".clickable").click(function() {
alert($(this).returnHTML());
});

$.fn.returnHTML = function() {
return $("<div/>").append($(this).clone()).html();
}
});

</script>
</
head>
<
body>
<
input id="btnClick" type="button" value="Click Me" class="clickable" />
<
br />

</
body>
</
html>

The example starts by capturing the click() event on elements which have the class=”clickable” attribute. The returnHTML() function clones the element and extract the html using html(). The result is appended to a div and returned to the calling function. The output is displayed in an alert() as shown below

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: