Skip to content Skip to sidebar Skip to footer

Why Can't I Add A
With Jquery .html?

Why does this code work: $('div.error_container').html('
No more foo allowed
'); But this code causes an error: $('div.error_container').html('&

Solution 1:

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);

Solution 2:

This works perfectly for me:

<!DOCTYPE htmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><scripttype="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script><scripttype="text/javascript">
$(function() {
  $('div.error_container').html('<div class="error">No more foo allowed<br /></div>');
});
</script></head><body><divclass="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>.

Solution 3:

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><htmllang="en"><head><title>SO question 2173556</title><scriptsrc="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><divid="foo"></div><divid="bar"></div></body></html>

Solution 4:

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.

Solution 5:

I had a similar problem and it had to do with the linking of jquery to my HTML file (the script tag wasn't up to date).

(Some newer features aren't compatible with an old version of Jquery, so when using Jquery we should always have the latest link. the SDN link should look like this:

<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Post a Comment for "Why Can't I Add A
With Jquery .html?"