LeBlaireau
LeBlaireau

Reputation: 17467

jquery append with large amount of html

I have been using $.get to get the contents of my lightbox

$.get('sidebar-lightbox.html', function(data, elem) {

//DO STUFF HERE
 });

I am looking for neat way to add large(ish), maybe 20 lines, of HTML into append. At the moment am doing

 $('.selector').append('<div id="wrapper"><div id="inner"><div id="content"></div></div></div>')

this is a bit messy and unreadable as the html gets bigger, looking for a nice way :).

Upvotes: 0

Views: 346

Answers (2)

David Hedlund
David Hedlund

Reputation: 129792

$('<div/>', { id: 'wrapper' }).appendTo('.selector');
$('<div/>', { id: 'inner' }).appendTo('#wrapper');
$('<div/>', { id: 'content' }).appendTo('#inner');

If you prefer, you could also have done something like:

$('<div/>', { id: 'wrapper' }).append(
    $('<div/>', { id: 'inner' }).append(
        $('<div/>', { id: 'content' })
     )
).appendTo('.selector')​;

You can of cours set any number of attributes here, remember to put the ones that are JavaScript keywords in strings, i.e. $('<div/>', { id: 'id', 'class': 'x' }). You could also chain multiple .attr and .html calls to get the markup you want.

Upvotes: 1

romainberger
romainberger

Reputation: 4558

Create a var first then append it. It will be more readable

var stuff = '<div id="wrapper">';
    stuff += '<div id="inner">';

// etc. then you append it
$('.selector').append(stuff);

Upvotes: 0

Related Questions