Farok Ojil
Farok Ojil

Reputation: 654

jquery - get text for element without children text

for example we have this file

<div id="mydiv">
    some text here 
    <div id="inner div">
         text for inner div
    </div>
</div>

i need to get #mydiv text only with some code like this :

alert($('#mydiv').text());  // will alert "some text here"

Upvotes: 26

Views: 19844

Answers (3)

Iv Ov
Iv Ov

Reputation: 380

Like Ja͢ck's answer but no need for iterating explicitly (via .each()) and collecting textContents:

$('#mydiv').contents().filter(function(){return this.nodeType === 3}).text()

OR, if you can use arrow functions:

$('#mydiv').contents().filter((i, el) => el.nodeType === 3).text()

Upvotes: 6

Ja͢ck
Ja͢ck

Reputation: 173522

The currently accepted answer is pretty horrible in terms of performance, so I felt obligated to write a more lightweight one:

$.fn.mytext = function() {
    var str = '';

    this.contents().each(function() {
        if (this.nodeType == 3) {
            str += this.textContent || this.innerText || '';
        }
    });

    return str;
};

console.log($('#mydiv').mytext());​

Upvotes: 26

Tats_innit
Tats_innit

Reputation: 34107

hey try this please": http://jsfiddle.net/MtVxx/2/

Good link for your specific case in here: http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/ (This will only get the text of the element)

Hope this helps, :)

code

jQuery.fn.justtext = function() {

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

};

alert($('#mydiv').justtext());​

Upvotes: 51

Related Questions