Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert html using jquery .html()

I want to insert a large chunk of html into a pre-existing <td>. I am using this method:

 $("td#content").html(LOTS_OF_HTML_CODE_HERE);

But it doesn't work. I am a noob, there are a lot of quotes and ' within the HTML chunk that seems to be breaking it. What is the correct method for doing this?

like image 894
Rob Bennet Avatar asked Aug 13 '10 18:08

Rob Bennet


2 Answers

Javascript doesn't have good support for multi-line strings or HEREDOC syntax, but there are a few workarounds.

Add a backslash "\" to the end of each line to let the script engine know you are continuing onto the next line without finishing:

<script>
var my_html = '\
    <div id="my-div">\
        <span>Name:</span> Your Name\
    </div>\
';
</script>

Use an XML CDATA hack(http://mook.wordpress.com/2005/10/30/multi-line-strings-in-javascript/):

<script>
var my_html = (<r><![CDATA[

    <div id="my-div">
        <span>Name:</span>Your Name
    </div>

]]></r>).toString();
</script>
like image 157
totels Avatar answered Sep 20 '22 12:09

totels


I would suggest unifying the html into one string... like so.

htmlStr = "";
htmlStr += "<p>some paragraph";
htmlStr += "<p>another paragaraph</p>";

$("#content").html(htmlStr);

this way you can see where your html is breaking down and it adds a lot of readability to javascript created content.

Also...

if there is content in this TD that you'd like to keep, I would use the append() jquery method.


the jquery documentation is your best friend!

like image 23
Derek Adair Avatar answered Sep 18 '22 12:09

Derek Adair