Michael Paccione
Michael Paccione

Reputation: 2827

How to turn string into HTMLCollection

I have static html stored in javascript string literal templates.

On button click, (modal popup) I need to pass the stored static html through a function and update elements in it with dynamic data that gets stored in a hidden div.

I need the html static string to become a HTML Collection, so I can perform jQuery functions on it for finding and replacing elements in it with the dynamic content stored in the hidden divs.

How do I do that?

Upvotes: 0

Views: 1471

Answers (3)

Donny West
Donny West

Reputation: 720

To answer your question in the comments as to how to accomplish this in plain JavaScript, you'd need to do the following:

var newDiv = document.createElement('div');
newDiv.className = 'foo';
var markup = '<p>blah blah blah...</p>';
newDiv.innerHTML = markup;

You can then do whatever you need to do with the new node, and insert it to the DOM with something like:

document.body.appendChild(newDiv);

Upvotes: 2

Harsh Yadav
Harsh Yadav

Reputation: 168

Let's say var HTMLAsString = "<div id="dynamicDivId">This is paragraph</div>" is the HTML which you want to add to modal

<div id="modalDivId">
    <div id="hiddenDivId">some data</div>
</div>

To get following output

<div id="modalDivId">
    <div id="hiddenDivId">some data</div>
    <div>some data</div>
</div>

You can do something like this

var dynamicDivSelector = $(HTMLAsString);
dynamicDivSelector.text($("#hiddenDivId").text());
$("#modalDivId").append(dynamicDivSelector);

Upvotes: 2

wscourge
wscourge

Reputation: 11301

var htmlString = "<div class='abc'><p>Lorem <strong>ipsum</strong> dolor sit amet..</p></div>";
var html = $(htmlString);

It creates an element wrapped in jQuery, so you can perform it's methods on it and when you're finished, you can append() it to your modal.

Upvotes: 3

Related Questions