Why can't I add a <br /> with JQuery .html?
Why does this code work:
$('div.error_container').html('<div class="error">No more foo allowed</div>');
But this code causes an err开发者_StackOverflowor:
$('div.error_container').html('<div class="error">No more foo allowed<br /></div>');
I've tried putting the <br />
before and after the </div>
tag, same error. I've tried changing it from <br />
to <br>
. Chrome always says the following in the inspector:
Uncaught SyntaxError: Unexpected token ILLEGAL
Try breaking it up into a chain:
var $div = $('<div class="error"></div>').html('No more foo allowed')
.append('<br />');
$('div.error_container').html($div);
This works perfectly for me:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('div.error_container').html('<div class="error">No more foo allowed<br /></div>');
});
</script>
</head>
<body>
<div class="error_container">
</div>
</body>
</html>
in Chrome and Firefox. What version of jQuery are you using?
On a side note <br />
is XML (including XHTML) not HTML. HTML is <br>
.
I tried the following SSCCE and it works flawlessly in IE, FF, Safari, Opera and Chrome (all of the most recent versions).
So your problem is likely related with the doctype you declared or using an old version of Chrome.
<!doctype html>
<html lang="en">
<head>
<title>SO question 2173556</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#foo').html('<div>foo<br>foo</div>');
$('#bar').html('<div>bar<br/>bar</div>'); // Yes, that's illegal in HTML strict. Just to test :)
});
</script>
<style>
</style>
</head>
<body>
<div id="foo"></div>
<div id="bar"></div>
</body>
</html>
I also had a similar issue, not sure if it is relevant. I was doing c# mvc for a cms.
So i had some html input from user and i display them using "@Html.Raw(Modal.Content)"
Inside the Modal.Content there was a <br />
and i had issue appending that content into the html using jquery .html("@Html.Raw(Modal.Content)")
But in the end the issue was not <br />
There is an invisible \n
so i did .html("@Html.Raw(Modal.Content).Replace("\n", "")")
and the issue was solved. The <br>
remained in my content and it work as expected.
精彩评论