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.

Example:

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.

EDIT:

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.

https://jsbin.com/ruwawuzica/edit?html,js,output

Answers


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

good luck!!!


Need Your Help

Date picker for command line

node.js datepicker command-line-interface vorpal.js

How are datepickers handled in a CLI environment? Is the most common route to just treat it as a text input with custom validation? Are there custom "controls" that keep formatting and only allow y...

Laravel Has Many Returns a Row even it has a value in relations table

php model laravel-5 eloquent

Hi I'm using laravel eloquent for my database query. My Problem is that I can't show the data I wanted to show. I have three tables. Say Users Table, Roles Table and User_Roles table.