views:

191

answers:

2

I think that this should be easy, but i'm not able to get it working. I want to target a div or other element using jQuery and then dinamically create a div containing the targeted element, for example:

jQuery ('.myclass')

how can i create a div with the background-color attribute set to white that contains 'myclass' element?

Initially i have: <div class="myclass">Some HTML elements inside</div>

And after executing the jQuery call i want to have: <div style="background-color:#fff"><div class="myclass">Some HTML elements inside</div></div>

I hope that you understand my question... thanks in advance

A: 
var $myDiv = $('<div>').css('background-color','#fff').append( $('.myclass') );

You can then write this variable to the DOM as you see fit, or do whatever else you need to do.

Stefan Kendall
Sorry, i've edited my question, now i hope that you can understand it better, there is more elements with same class into the HTML, there is no only one. I want to have all elements with the given class with a surrounding div with white background.
fidoboy
This should probably still work.
Stefan Kendall
The answer by tvanfosson will work better for an in-place edit, if that's what you're trying to achieve.
Stefan Kendall
+3  A: 

You can use the wrap function to put a wrapper around the matching elements. I'd prefer to use a class for the background, but you can assign CSS properties directly as well.

$('.myclass').wrap( $('<div></div>').css( 'background-color', '#fff' ) );

or

$('.myclass').wrap( $('<div></div>').addClass('white-background') );
tvanfosson
+1 But ... 'white-background' is not a very semantic class name. Something like 'highlighted' or 'selected' would be better, depending on the reason for the white background. /pedantry
brianpeiris
Agreed - though I didn't have much to work with other than the background needed to be white.
tvanfosson