user599146
user599146

Reputation: 344

jQuery's HTML() Function Decodes HTML Entities

Is there any way to get the HTML of an element without having the HTML Entities decoded?

I'm using jQuery's .html() method currently but it decodes HTML entities

Upvotes: 1

Views: 2195

Answers (3)

Plippie
Plippie

Reputation: 2886

I was struggling with the same problem I was using a wyswyg editor and when using

<texarea id="htmlsource"><p>hello html</p></textarea>

<script>
var source= $("#htmlsource").html();
alert(source);
</script>

It encoded the HTML to &ltp&gt Hello world &lt/p&gt This was not what i'am expecting when using the .html() function. Logically you would expect the output the be HTML and not a encoded string for readable text.

I tested this in Chrome, IE9 and Firefox7 all with the same outcome. To fix this you can use the .text() function. Crazy right?!

<texarea id="htmlsource"><p>hello html</p></textarea>

<script>
var source= $("#htmlsource").text();
alert(source);
</script>

So the answer is YES you can.

Update: I have created a definitive guide to solutions as a fiddle here.

Upvotes: 1

Jason Spick
Jason Spick

Reputation: 6098

Ok, So I think I have an answer to your problem.

I was using ajax to go through xml files and create code in a text area to be copied into an html file. Don't ask why, I'll just say IT is restrictive here. Anyway, the list of links needed to look like this:

<a href="link.html#!page=01">Something</a>

well .html() was making it look like this:

<a href="link.html#%21page=01">Something</a>

This Caused problems with page loading. I guess the browser changes %21 => ! after the page loads.

What you need to do is make a variable out of what you want to .html() like this:

var prepReplaceEscape = $("#prep").html();

Then to put it in the place you want and use .replace() :

$("#output").text(prepReplaceEscape.replace(/%21/gi,"!"));

It's important to have /%21/gi this allows the .replace() method to keep going through the var. "%21" being what you want to replace.

I hope this helps. It's kinda messy but it worked for me.

If anyone has a better solution please let me know, I would love to know.

Upvotes: 0

Murali VP
Murali VP

Reputation: 6427

it is not JQuery doing it but the browser's HTML parser. So the answer is no.

Upvotes: 2

Related Questions