When I add HTML to a div
element and later try to get it back, jQuery either removes the HTML tags or converts all applicable characters to HTML entities, depending on if I use .html()
or .text()
.
Here's a demonstration (jsfiddle)
$('div').html('<h1>Hi, Alice & Bob</h1>');
console.log('html: ' + $('div').html());
console.log('text: ' + $('div').text());
Console output
html: <h1>Hi, Alice & Bob</h1>
text: Hi, Alice & Bob
How do I get back exactly <h1>Hi, Alice & Bob</h1>
?
I don't know any other way to solve this other than to decode the entities like so
var decode = function( val ) {
var el = document.createElement('textarea');
el.innerHTML = val;
return el.value;
};
Here is a function that will do that for you
and usage like this
$('div').html('<h1>Hi, Alice & Bob</h1>');
console.log( decode( $('div').html() ) );
// Result is => <h1>Hi, Alice & Bob</h1>