这是CMS动态生成的HTML:
<DIV CLASS="messageContent">
<BLOCKQUOTE CLASS="messageText">
<IMG ALT="image" CLASS="myimage" SRC="http://...." STYLE="">
<BR> and more recently with desktop publishing<b> software like Aldus PageMaker/<b>including versions of Lorem Ipsum
</BLOCKQUOTE>
</DIV>
我尝试使用此函数用div包装整个文本:
$('blockquote.messageText').contents()
.filter(function(){return this.nodeType === 3})
.wrap('<div />');(found it in http://stackoverflow.com/ but don't remember where)
但是,上面的函数在div中包含太多元素甚至包装空格,结果如下:
<DIV CLASS="messageContent">
<div> </div>
<BLOCKQUOTE CLASS="messageText">
<IMG ALT="image" CLASS="myimage" SRC="http://...." STYLE="">
<BR>
<div> and more recently with desktop publishing </div>
<b> software like Aldus PageMaker/<b>
<div>including versions of Lorem Ipsum</div>
</BLOCKQUOTE>
</DIV>
那么如何只在一个div中包装文本? 这是预期的HTML:
<DIV CLASS="messageContent">
<BLOCKQUOTE CLASS="messageText">
<IMG ALT="image" CLASS="myimage" SRC="http://...." STYLE="">
<DIV>
<BR> and more recently with desktop publishing<b> software like AlduPageMaker/<b>including versions of Lorem Ipsum
</DIV>
/BLOCKQUOTE>
</DIV>
答案 0 :(得分:1)
假设结构与示例中的结构一样,您可以使用:
var img = $('blockquote.messageText img');
$('blockquote.messageText img').remove()
$('blockquote.messageText').wrapInner('<div>').prepend(img);
哪会产生:
<div class="messageContent">
<blockquote class="messageText">
<img alt="image" class="myimage" src="http://...." style="">
<div>
<br>and more recently with desktop publishing<b> software like Aldus PageMaker</b>including versions of Lorem Ipsum</div>
</blockquote>
</div>
<强> jsFiddle example 强>