26

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"
Farok Ojil
  • 664
  • 1
  • 12
  • 22
  • So you want *all* child text nodes, without more deeply nested text nodes? –  Jul 06 '12 at 12:33

3 Answers3

51

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());​
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
25

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());​
Community
  • 1
  • 1
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • 1
    Much better! I was looking for a way to iterate over each child of selected element, and I didn't know about `contents()`, thanks! – mr.b Oct 16 '14 at 23:07
5

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()
Iv Ov
  • 357
  • 3
  • 6