views:

51

answers:

3

How do I get the HTML that makes up an element using Jquery or Javascript? For example if I have an element that looks like

<div id="theDivIWant" class="aClassName" style="somestyle: "here"></div>

I can grab a reference to it using

var x = document.getElementById("theDivIWant") or $("#theDivIWant")

but how can I actually retrieve the string?

"<div id="theDivIWant" class="aClassName" style="somestyle: "here"></div>"
+4  A: 

the outerHTML property will give you what you want in IE; in webkit and firefox, you can get the innerHTML of the parent and filter it:

var whatYouWantPlusItsSiblings = $('#target').closest().html();

From there, you can strip the content you don't need. Alternatively, if you have control over the markup, you can surround your target with another well-known element and get that parent's innerHTML.

DDaviesBrackett
May be worth noting that outerHTML is part of HTML5 now, and is also supported in Chrome and Safari.
Anurag
+2  A: 

You could implement outerHTML with jQuery.

Darin Dimitrov
+2  A: 

if it is the only child of its parent, this should work:

$('#theDivIWant').parent().html();

If it is not the only child, you may be able to combine the above code with some regex to extract only it from the results.

John Isaacks