1

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>"

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

You could implement outerHTML with jQuery.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.