Reputation: 5176
Why is that code like $('#display').append('    dogs');
appends "    dogs" while $('#display').append('    dogs <br/>');
(or adding any html tag) appends just "dogs" after two spaces (as expected)? Does jQuery not recognise ' ' as an html entity? Can I somehow force treating it like html?
$('#display').append('    dogs</br>');
$('#display').append('    dogs <span>hi</span>');
$('#display').append('</br>');
$('#display').append('    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
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     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  
into
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     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