Search code examples
jqueryhtmlutf-16

Why does JQuery only display HTML characters when enclosed in other tags?


I'm curious about why this JQuery renders the full block HTML character:

var html = $('<div>&#9608;</div>');
$("body").append(html)

But this doesn't:

var html = $('&#9608;');
$("body").append(html)

Is there a way to render one single special character (by HTML or hex) without enclosing tags?

JSFiddle here: http://jsfiddle.net/G2Km8/2/


Solution

  • I think this is because JQuery treats your second case as a CSS selector rather than an HTML fragment. Since you probably don't have any elements matching "&#6908;" in your document, you are basically appending an empty set of elements to your body.

    try using directly

    $("body").append('&#9608');
    

    This prevents JQuery from having to guess if your string is and HTML fragment or a CSS selector. When passed a String, the append method assumes it is an HTML fragment.