jQuery选择文本节点并删除其内容

时间:2013-09-09 08:33:48

标签: jquery text selection nodes

我正在寻找这个问题的答案,我想出了这个

stackoverflow - How do I select text nodes with jQuery?

到目前为止还有另一种方法吗? 在我的情况下,我试图从给定的DOM元素和

开始查找每个文本节点
empty()

它。有什么建议吗?

更新 - 在一点点搞乱后我想出了这个 jsFiddle

现在该函数选择每个文本节点,但不是仅用给定的新值替换空的节点,而是替换所有这些节点。 我做错了什么?

5 个答案:

答案 0 :(得分:2)

参考这个'现在该函数选择每个文本节点,但不是仅用给定的新值替换空的节点,而是替换所有这些节点。我做错了什么?'

需要的是,只需使用正则表达式测试nodeValue的空格,然后再继续前进。

我已经像这样更新了它并且工作正常http://jsfiddle.net/Vj5LR/2/

$(document).ready(function(){

   var prova = ['1','2','3','4','5','6'];
   var regForNonWhiteSpace = /\S/; // non white space
   $('.example').find('*').each(function(){
       $(this).contents().filter(function(){
           //this.trim();
           if( this.nodeType === 3 && !regForNonWhiteSpace.test(this.nodeValue)){
               this.nodeValue = 'new value'; // only when there is no content at all
           }
       });
    });
});

希望这能解决问题

答案 1 :(得分:1)

empty()用于清空元素的innerText,不适用于textNodes。相反,您需要使用remove()

$('.example')
    .contents()
    .filter(function () {
    return this.nodeType === 3; //Node.TEXT_NODE
}).remove();

Example fiddle

答案 2 :(得分:1)

$(document).ready(function(){

    var prova = ['1','2','3','4','5','6'];

    $('.example').find('*').each(function(){
        $(this).contents().filter(function(){
            //this.trim();
            if( this.nodeType === 3 && this.nodeValue.trim().length === 0){
                this.nodeValue = 'new value';
            }
        });
    });
});

http://jsfiddle.net/trevordowdle/RajB4/40/

答案 3 :(得分:1)

这个演示http://jsfiddle.net/RajB4/42/

怎么样?
if( this.nodeType === 3 && this.nodeValue.trim().length != 0){
                this.nodeValue = 'new value';
            }

答案 4 :(得分:0)

据我了解,我认为这就是你要找的东西:

$('.example').each(function(){
    console.log($(this).contents());
    $(this).contents().filter(function(){
        if( this.nodeType === 1 && this.childElementCount == 0 && this.textContent == ''){
            this.textContent = 'new value';
        }
    });
});

您可以查看fiddle

相关问题