Cyber Junkie
Cyber Junkie

Reputation: 766

Get raw HTML from a div using js?

I'm working on a website where users can create and save their own HTML forms. Instead of inserting form elements and ids one by one in the database I was thinking to use js (preferably jquery) to just get the form's HTML (in code source format) and insert it in a text row via mysql.

For example I have a form in a div

<div class="new_form">
<form>
Your Name:
<input type="text" name="something" />
About You:
<textarea name=about_you></textarea>
</form>
</div>

With js is it possible to get the raw HTML within the "new_form" div?

Upvotes: 3

Views: 18188

Answers (3)

bobince
bobince

Reputation: 536339

Note when you use innerHTML or html() as above you won't get the exact raw HTML you put in. You'll get the web browser's idea of what the current document objects should look like serialised into HTML.

There will be browser differences in the exact format that comes out, in areas like name case, spacing, attribute order, which characters are &-escaped, and attribute quoting. IE, in particular, can give you invalid HTML where attributes that should be quoted aren't. IE will also, incorrectly, output the current values of form fields in their value attributes.

You should also be aware of the cross-site-scripting risks involved in letting users submit arbitrary HTML. If you are to make this safe you will need some heavy duty HTML ‘purification’.

Upvotes: 4

BrunoLM
BrunoLM

Reputation: 100322

To get all HTML inside the div

$(".new_form").html()

To get only the text it would be

$(".new_form").text()

You might need to validate the HTML, this question might help you (it's in C# but you can get the idea)

Upvotes: 11

Hammerite
Hammerite

Reputation: 22340

Yes, it is. You use the innerHTML property of the div. Like this:

var myHTML = document.getElementById('new_form').innerHTML;

Upvotes: 4

Related Questions