在div中包装流浪文本 [英] Wrap stray text in divs

查看:36
本文介绍了在div中包装流浪文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何选择没有包含标签的任何内容"以在jQuery中添加包装器?例如:

How do I select "anything that doesn't have a containing tag" to add a wrapper in jQuery? ex:

<div class="post">
    <div class="whatever">This should remain untouched</div>
    I want to wrap this in div.red
</div>

结果就是这样

<div class="post">
    <div class="whatever">This should remain untouched</div>
    <div class="red">I want to wrap this in div.red</div>
</div>

推荐答案

您正在尝试选择文本节点.试试这个(小提琴):

You are trying to select the text nodes. Try this (fiddle) :

$('.post').each(function() {
    var data = [];
    $(this).contents().each(function() {
        if ( this.nodeType === Node.TEXT_NODE ) {
            data.push(this);
        }
    }).end().append( $('<div class="red" />').append(data) );
});

HTML :

<div class="post">
    <div class="whatever">This should remain untouched</div>
    I want to wrap this in div.red
</div>

CSS :

.red{background:red}

这篇关于在div中包装流浪文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆