Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 255
user2950747 Avatar asked Nov 03 '13 21:11

user2950747


2 Answers

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.

like image 197
LordOfThePigs Avatar answered Oct 22 '22 20:10

LordOfThePigs


You don't need the $ sign for the var

Check this:

http://jsfiddle.net/G2Km8/4/

$(document).ready(function(){
  $("button").click(function(){
    var html = "&#9608;";
    $("body").append(html);
  });
});
like image 24
Hasan Alaca Avatar answered Oct 22 '22 21:10

Hasan Alaca