Fabien from Paris
Fabien from Paris

Reputation: 13

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 !

Upvotes: 1

Views: 98

Answers (3)

voigtan
voigtan

Reputation: 9031

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/

Upvotes: 0

Dominic Green
Dominic Green

Reputation: 10258

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

Upvotes: 1

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

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/

Upvotes: 5

Related Questions