简体   繁体   中英

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". 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/

Hey try this instead what you want to do is clone your element then remove your child elements

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)

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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