matteking matteking - 1 month ago 7
jQuery Question

Prevent jQuery .html() from removing self closing tag slash

I'm sure most of you know the following:

var str = '<img src="path/to/some/image" />'

$('#selector').html(str);


This will output the following HTML:

<div id="selector">
<img src="path/to/some/image">
</div>


It removes the self closing "slash" at the end of the img tag because jQuery renders true HTML, not XHTML.

My hands are tied into using a CMS that validates against XHTML so any markup that is copied into or created in the systems WYSIWYG must contain the "slash" at the end of a self closing tag.

My predicament is that I am using the Bootstrap Form Builder to create some quick and dirty forms. This application uses the jQuery .html() to create the rendered HTML. So all the < input > closing tag slashes are being stripped. When I copy and paste the rendered code into my CMS, it won't let me published it.

Anybody have a clever way to prevent .html() from removing the "slashes"? Or at least putting the slashes back in without having to manually do it?

Answer

I figured it out! Well, my co-worker did :)

There are a couple extra layers to this since I am using a Form Builder that is rendering the HTML to a textarea.

I had to use a combination of .text() and .html(). Instead of explaining it, here is a code snippet and jsfiddle link which showcases a very simplified version of what is going on:

$('#html').html("<input type='text' />");
var str = $('#html').html();
$("#renderHTML").html(str);

This will output <input type='text'>

$('#text').text("<input type='text' />");
var str1 = $('#text').text();
$("#renderTEXTHTML").html(str1);

And this one will output This will output <input type='text' />

http://jsfiddle.net/xMsgg/1/

Comments