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

No comments:

Post a Comment