Click here to Skip to main content
16,012,468 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have created image element dynamically. I want to set background color of the image element. it is not working for the following code.
var img = $('<img />', {
                id: 'img1',
                src: '/ProductImages/' + products[1].PictureFileName
            }).appendTo(span);
            img.width(150); img.height(200);
            img.css('background-color', '#efeeef');
            img.className = 'bkcolor';
Posted
Updated 10-Jan-16 14:08pm
v2
Comments
Sergey Alexandrovich Kryukov 10-Jan-16 21:29pm    
Why do you modify both CSS and class? They may contradict to each other.
The "problems" is way too simple.
—SA
Member 7854207 10-Jan-16 23:39pm    
i tried either way css and class. it is not working.

1 solution

Please see my comment to the question. I would not use jQuery way here. The native HTML element object does in better, more maintainable manner which is also supported by Visual Studio Intellisense. Instead of two last line, I would write
JavaScript
img.style.backgroundColor = //... some color

Please see: HTMLElement.style - Web APIs | MDN[^].

Note that this style will be applied on top of the style already applied to the element. Also note that this color has nothing to do with the content of the image; you won't see any color difference if the image fully fills the img element, so, to see it, you either need to have semi-transparent image, or some padding inside img. It could be another (way too trivial) reason why you may not see the difference.

—SA
 
Share this answer
 
Comments
Member 7854207 11-Jan-16 4:09am    
I am sure that each image has its background color. in my project I want to change it. I tried with img.style.backgroundColor. but it is not working.
Sergey Alexandrovich Kryukov 11-Jan-16 9:49am    
No. There is no such thing.
—SA
Member 7854207 11-Jan-16 5:12am    
thank you for your valuable comment. I saw the image is actually padded with white color.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900