Theodore K.
Theodore K.

Reputation: 5176

Append non-breaking space behaviour

Why is that code like $('#display').append('&nbsp &nbsp dogs'); appends "&nbsp &nbsp dogs" while $('#display').append('&nbsp &nbsp dogs <br/>'); (or adding any html tag) appends just "dogs" after two spaces (as expected)? Does jQuery not recognise '&nbsp' as an html entity? Can I somehow force treating it like html?

$('#display').append('&nbsp &nbsp dogs</br>');
$('#display').append('&nbsp &nbsp dogs <span>hi</span>');
$('#display').append('</br>');
$('#display').append('&nbsp &nbsp dogs');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="display"></div>

Upvotes: 0

Views: 1447

Answers (1)

Dekel
Dekel

Reputation: 62596

jQuery's append function accept several content-types as the content to append

htmlString, Element, Text, Array, jQuery.

When you use the a string with tags inside - jQuery treats the string as htmlString, and converts it to html:

$('#display').append('<span style="color: red;">a &nbsp &nbsp dogs</sapn>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="display"></div>

This conversion also converts the typo &nbsp into &nbsp;

However, if jQuery doesn't recognize the string as html-string, it treats it as text (and creates a textNode with the string):

$('#display').append('a &nbsp &nbsp dogs');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="display"></div>

This behavior is the same in Chrome, Firefox, IE(11) and Safari.

Upvotes: 2

Related Questions