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"
1
  • So you want all child text nodes, without more deeply nested text nodes?
    – user1106925
    Commented Jul 6, 2012 at 12:33

3 Answers 3

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());​
3
  • 7
    +1 for using .end(). Never knew that existed and now it's hella-usefull.
    – Grinn
    Commented Aug 7, 2012 at 18:43
  • @Grinn saweet bruv, yea there are some jq apis, which are awesome to use but not widely used, :) funny that huh, thanks for plus 1.
    – Tats_innit
    Commented Aug 7, 2012 at 19:10
  • this seems to crash in Win XP IE 8, something around clone or children still trying to figure this out.. Commented Mar 20, 2014 at 15:08
26

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());​
1
  • 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
    Commented Oct 16, 2014 at 23:07
6

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.