Append HTML to HTML string in jQuery
I have a HTML string and I want to append another html string to this in some arbitrary location.
var htmlString = '<div id="insert"> <p> Hello </p> </div>' var appendString = '<p> Goodbye </p>' $(appendString).appendTo( $(htmlString).find('#insert') )
Obviously that doesn't work because it cannot insert directly into the string however, I do not want to convert htmlString into a jQuery object because it messes up the structure of the HTML document and I need the script tags to remain in the locations they have been inserted.
Hope that's clear enough.
My apologies, I think I explained my problem poorly.
I have a HTML string that includes a table and I want to append a new row to the table. My problem is that I have a number of <script> tags that I need to remain in their locations. When I convert the string into a $(string), I am then unable to return it to its original form:
var htmlString = $('body').html(); var $htmlString = $(x); console.log($htmlString.html());
This is a Confluence page that I attempting to do this on and I have limited access to the source; most I can do is to modify what is already there.
The HTML string comes from a AJAX request of another page on Confluence and I need the scripts to remain in the same place so that my other macros will run correctly.
I have included a JS Bin example of my problem to hopefully illustrate my problem clearly.
You can do it like this:
var htmlString = '<div id="insert"> <p> Hello </p> </div>'; var appendString = '<p> Goodbye </p>'; var added = ($(htmlString).append($(appendString))); $(added).appendTo('div');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div></div>
Hi @MyLittleDax i guess you can do this:
var htmlString = "<div id='insert'> <p> Hello </p> </div>"; var appendString = "<p> Goodbye </p>"; //your container where you put the html var container = $('#container'); container.empty(); container.append(htmlString); var insert = $('#insert'); insert.append(appendString);