简体   繁体   English

使用jQuery创建一个包含目标div的div

[英]Create a div containing target div using jQuery

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定位div或其他元素,然后动态创建一个包含目标元素的div,例如:

jQuery ('.myclass') jQuery('.myclass')

How can I create a div with the background-color attribute set to white that contains 'myclass' element? 如何创建一个将div的background-color属性设置为白色的div,其中包含“ myclass”元素?

Initially I have: <div class="myclass">Some HTML elements inside</div> 最初我有: <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> 在执行jQuery调用后,我希望拥有: <div style="background-color:#fff"><div class="myclass">Some HTML elements inside</div></div>

I hope that you understand my question... 我希望你能理解我的问题...

You can use the wrap function to put a wrapper around the matching elements. 您可以使用wrap函数在匹配的元素周围放置包装器。 I'd prefer to use a class for the background, but you can assign CSS properties directly as well. 我希望使用一个类作为背景,但是您也可以直接分配CSS属性。

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

or 要么

$('.myclass').wrap( $('<div></div>').addClass('white-background') );
var $myDiv = $('<div>').css('background-color','#fff').append( $('.myclass') ); 

然后,您可以根据需要将此变量写入DOM,或执行其他任何需要做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM