Using jquery to dynamically create a div

I am trying to add a background image to a dynamically generated div. When I add the CSS property for the background, as shown below, it breaks my plugin:

$("<div>", { 'class': "iviewer_image_mask", css: "background: url('http://somesite.com/path/to/image.jpg');" }).appendTo(this.container); 

Does anyone know what I'm doing wrong to add a background image?

+8
jquery
source share
4 answers

According to some benchmarking mentioned in this question overflowing https://stackoverflow.com/a/212960/289 , I believe that the most efficient way to create your HTML element using jQuery would be as follows:

 $('<div class="iviewer_image_mask" style="background: url(http://somesite.com/path/to/image.jpg);"></div>').appendTo(this.container); 

Or for some extra readability:

 var elm = '<div class="iviewer_image_mask" ' + 'style="background: url(http://somesite.com/path/to/image.jpg);">'+ '</div>'; $(elm).appendTo(this.container); 
+13
source share

Of course, you can only add it with a string, but I prefer this method because it is much more readable and cleaner.

 $("<div>", { 'class': "iviewer_image_mask", css: { "background": "url('http://somesite.com/path/to/image.jpg')" } }).appendTo(this.container); 

demo

+18
source share
 $("<div>").attr({ 'class': "iviewer_image_mask", 'style': "background: url('http://somesite.com/path/to/image.jpg');" }).appendTo("body"); 

If you really need to apparate it by attributes.

+4
source share
 $("<div>") .addClass('iviewer_image_mask') .css('background', "url('http://somesite.com/path/to/image.jpg')") .appendTo(this.container); 
+3
source share

All Articles