Reputation: 7814
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>"
Upvotes: 1
Views: 121
Reputation: 58014
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.
Upvotes: 2
Reputation: 10081
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.
Upvotes: 4