4

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

2 Answers 2

4

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>

Since $(htmlString) is the element <div id="insert"></div> wrapped in jquery

Sign up to request clarification or add additional context in comments.

1 Comment

What exactly asked in question was how we can insert good by a string in id="insert" part of HTML but what you have suggested is how we can append the html.
2

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!!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.