We help IT Professionals succeed at work.

.html() not decoding html elements

nzinsli
nzinsli used Ask the Experts™
on
I have a string that has some encoded html characters...
str = '<br />'

Open in new window

And I'm using jQuery to fill an elements' html with that string...
$('#element').html(str);

Open in new window

But when I view it in the browser I get "<br />" instead of a line break. I thought html() should decode everything into html formatting?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
it probably because it does not see that string as html, the browser is what is translating the &lt; and the &gt; into <  and >.
That isn't what html() does.  See you were to do something like this...

$('selection').text('<br />')

It would put those exact characters into the element.  But html() is used to add in actual html to the page and have the page render it as html.  so if you were to put in...

$('selection').html('<br />')

it would actually render it as a line break.  Now, what you are doing is putting in text that has been character coded.  When you put that into the html() element it is legitimately not seen as html and renders to the page exactly as you pass it though.  You'll need to translate that back into standard html before you pass it into the html method.

Here is a tool that you might want to use to accomplish this...

Source Code js file:
http://www.strictly-software.com/scripts/downloads/encoder.js

Demo:
http://www.strictly-software.com/htmlencoder

Author

Commented:
Ahh, that makes sense now. I should've realized that. Thanks!