1

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 dynamically 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...

2 Answers 2

3

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') );
Sign up to request clarification or add additional context in comments.

2 Comments

+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
Agreed - though I didn't have much to work with other than the background needed to be white.
0
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.

2 Comments

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.
The answer by tvanfosson will work better for an in-place edit, if that's what you're trying to achieve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.