tags:

views:

59

answers:

2

Hello, I have the following html:

<div id="box">
<span>stuff.....</span>
</div>

What i'd like to do is create a JavaScript variable with this html... Then with jQuery be able to insert that into the page with something like $('#contentCol').html(mystuff)

Is there an elegant way to do this rather than a long string of html?

A: 

in simple javascript you can use createElement and appendChild element etc to create DOM elements at runtime. in jQuery you can do it like

jQuery('<div id="box">...</div>').appendTo('#contentCol');

sushil bharwani
thanks but that's not elegant, it's repeating closing tags etc... Just wondering if there is a cleaner way. thanks for the answer.
AnApprentice
+1  A: 

ID names are unique, so I changed id="box" to class="box", so you can insert the block multiple times.

Simply create a function that returns a jQuery object of the type you want. You can pass the HTML inside the span to the function as an argument:

function createBlock(myHTML) {

    $("<div/>").attr("class", "box").append($("<span/>").html(myHTML));
}

You can use this function in multiple ways:

// Method 1:
var myStuff = createBlock("stuff");
$("body").append(myStuff);
  // or even...
$('#contentCol').html(myStuff)

// Method 2:
$("body").append(createBlock("other stuff"));

// You can of course append wherever you want... or prepend, or before / after
//   or use the jQuery object to build up an even larger block before inserting.

jsFiddle example

Peter Ajtai