简体   繁体   English

如何在jQuery中仅选择包含其他div的div中的文本?

[英]How to select only text in a div containg other div in jQuery?

I have this code : 我有这个代码:

<div class="bodytext1typeenc">Ce qu’il faut retenir
    <div class="al">Budget «solidarités».</div>
</div>

I want to get only "Ce qu'il faut retenir". 我只想获取“ Ce qu'il faut retenir”。 I've tried this : 我已经试过了:

$('.bodytext1typeenc').text() // --> doesn't work.
$('.bodytext1typeenc').remove('.al') //  --> doesn't work.

Any help please ? 有什么帮助吗? Thanks ! 谢谢 !

You could clone, remove the children and get the text. 您可以克隆,删除子级并获取文本。 See below, 见下文,

var $clone = $('.bodytext1typeenc').clone();
$clone.children().remove()
$clone.text(); //should return the div's text

Note: You don't need to clone if you don't want to preserve the original content. 注意:如果您不想保留原始内容,则无需克隆。

DEMO: http://jsfiddle.net/PX2yA/ 演示: http : //jsfiddle.net/PX2yA/

Hey try this instead what you want to do is clone your element then remove your child elements 嘿,尝试一下,您要做的就是克隆您的元素,然后删除您的子元素

http://jsfiddle.net/HgdyG/ http://jsfiddle.net/HgdyG/

$(".bodytext1typeenc")
        .clone()    //clone the element
        .children() //select all the children
        .remove()   //remove all the children
        .end()  //again go back to selected element
        .text();

If you where going to use this alot you could create a simple extension like this 如果您打算在这里大量使用它,则可以创建一个简单的扩展,例如

jQuery.fn.noChild= function() {

    return $(this).clone()
            .children()
            .remove()
            .end()
            .text();

};

Then run 然后跑

$(".bodytext1typeenc").noChild();

You could use contents() and filter out the noteType TEXT_NODE (3) 您可以使用contents()并过滤出noteType TEXT_NODE(3)

var val = $('.bodytext1typeenc').contents().filter(function() {
  return this.nodeType == 3;
}).text();
val = $.trim(val);

alert('"' + val + '"'); // "Ce qu’il faut retenir"

demo: http://jsbin.com/AsilIpo/1/ 演示: http : //jsbin.com/AsilIpo/1/

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

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