Steve
Steve

Reputation: 4918

Inserting a newly created div into the DOM

I want to append the div below, which has two children, to a #galleryHeader div in the DOM.

 <div class=open_folder_icon>
            <img class="folder_icon" src="images/folder_open.png"  alt="open folder"  />
            <div class="folder_name" >Root</div>
     </div>

I want to do something like

$('<div>').appendTo(#galleryHeader);   

but replace the simple 'div' here with my more complicated div. Is there a clean way to do that?

Thanks

Upvotes: 0

Views: 29

Answers (2)

Los Frijoles
Los Frijoles

Reputation: 4821

Not sure what the question is, but If its about append:

It should go the other direction using append:

$('#galleryHeader').append('<div>');

where <div> is your more complicated div as a string.

See documentation here.

Alternately, you should be able to do:

$('<div>').appendTo('#galleryHeader');

In either case, you need to make sure your #galleryHeader is in quotation marks since it is acting as a selector.

If the question is about creating the complicated div:

jQuery lets you create an element from a string quite easily. Just construct the element in a string like:

var myDiv = '<div class=open_folder_icon>' +
    '<img class="folder_icon" src="images/folder_open.png"  alt="open folder"  />' +
    '<div class="folder_name" >Root</div>' + 
    '</div>';

and then use it in the jQuery statement:

$(myDiv).appendTo('#galleryHeader')

You can also directly place the div as a string into the $() expression, but I personally think that placing it in its own variable and constructing it line by line is easier to read than a huge one-liner of HTML.

Another option is that you could use a templating engine such as underscore or handlebars to generate the string that you feed jQuery.

Under the hood, jQuery is calling the appropriate DOM functions to create your HTML as DOM element objects from the string that you pass it.

Upvotes: 1

Velimir Tchatchevsky
Velimir Tchatchevsky

Reputation: 2825

You should also escape the quotes the example below is your complicated div with escaped quotes and it works. Also you forgot to put quotes around the "open_folder_icon" class

$("#galleryHeader").append("<div class=\"open_folder_icon\"><img class=\"folder_icon\" src=\"images/folder_open.png\"  alt=\"open folder\"  /><div class=\"folder_name\" >Root</div></div>");

Upvotes: 0

Related Questions