AnApprentice
AnApprentice

Reputation: 111030

jQuery, creating an HTML block that I can insert into the page

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?

Upvotes: 3

Views: 10846

Answers (3)

cristianego
cristianego

Reputation: 81

its work for me

in html file have a div like

<div class="demo">
  <div class="demo">Demonstration </div>
</div>

and selector of class is '.demo'

$('.demo').html('<form>Name:<input type="text" id="name">'+
        '<br>Pass:<input type="text" id="pass">'+
        '<br><input type="submit" value="confirm"></form>');

this replace "<div class="demo">Demonstration </div>" for

"<form>Name:<input type="text" id="name">'+
        '<br>Pass:<input type="text" id="pass">'+
        '<br><input type="submit" value="confirm"></form>"

Upvotes: 0

Peter Ajtai
Peter Ajtai

Reputation: 57695

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

Upvotes: 6

sushil bharwani
sushil bharwani

Reputation: 30197

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

Upvotes: 0

Related Questions