簡體   English   中英

如何在jQuery中僅選擇包含其他div的div中的文本?

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

我有這個代碼:

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

我只想獲取“ Ce qu'il faut retenir”。 我已經試過了:

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

有什么幫助嗎? 謝謝 !

您可以克隆,刪除子級並獲取文本。 見下文,

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

注意:如果您不想保留原始內容,則無需克隆。

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

嘿,嘗試一下,您要做的就是克隆您的元素,然后刪除您的子元素

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();

如果您打算在這里大量使用它,則可以創建一個簡單的擴展,例如

jQuery.fn.noChild= function() {

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

};

然后跑

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

您可以使用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"

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM