jQuery: Get the Text of Element without Child Element

jquery-logoWhile writing code in jQuery, I often use .text() method to get the content of any element from DOM. This function is straight forward, it strips off all the html element from a selected element and returns the remaining text. So for below element the .text() method will return “A quick brown fox”.
<div id="foo"> A quick brown fox </div> <script> $("#foo").text(); //return "A quick brown fox" </script>
Code language: HTML, XML (xml)
But by the definition the .text() returns all the text inside an element. What if you have an element which contains child elements and you want text of only the selected element ignoring all the child elements? For example: Here we have a DIV which has text “A quick brown fox” and also contain a child DIV which has text “jumps over a lazy dog!”
<div id="foo"> A quick brown fox <div id="bar"> jumps over a lazy dog! </div> </div> <script> $("#foo").text(); //return "A quick brown fox jumps over a lazy dog!" </script>
Code language: HTML, XML (xml)
What if you just want “A quick brown fox” and wants to ignore all the child element? Well, here is a simple solution using jQuery.
<script> $("#foo") .clone() //clone the element .children() //select all the children .remove() //remove all the children .end() //again go back to selected element .text(); //get the text of element </script>
Code language: JavaScript (javascript)
We clone the element that you want text of, then remove all the child elements from this cloned element and then returns the text of element. I have written a small jQuery plugin “justtext” which you can use to get the text of element and ignore all child elements. Here is the code of justtext plugin.
jQuery.fn.justtext = function() { return $(this) .clone() .children() .remove() .end() .text(); };
Code language: JavaScript (javascript)
So the usage is just by calling justtext() method on any element.
<!-- include justtext jquery plugin --> <script src="https://www.viralpatel.net/demo/jquery/get-text-without-child-element/jquery.justtext.1.0.js"></script> <div id="foo"> A quick brown fox <div id="bar"> jumps over a lazy dog! </div> </div> <script> $("#foo").justtext(); //return "A quick brown fox" </script>
Code language: HTML, XML (xml)

Online Demo

Online Demo Link
Get our Articles via Email. Enter your email address.

You may also like...

25 Comments

  1. Viet says:

    An nice and useful tutorial. Thanks.

  2. Name says:

    this works great if you only have one orphan child, but it stops when you have multiple lines of text and they are in different areas within the container. :)

  3. Alex says:

    jQuery noob here. I just spent around half an hour looking for a simple solution to a simple problem I was trying to solve, but nothing really worked until this article got me on the right track. Just wanted to say thanks, is all. :)

  4. jayd says:

    awesome. short and sweet AND reusable. Just what I was looking for.. thanks.

  5. Joedel says:

    This is what I looking for.

    Thank you very much.

  6. mahesh says:

    Nice example, thanks for sharing. Am sure it would go in *.util of most projects :).

  7. Mat says:

    well done

  8. Thanks – simple but effective. As mahesh said, one for the the util file!

  9. pranay says:

    Nice example, thanks for sharing
    but how to create .justtextUpdate()

  10. SM says:

    Thanks man :) cute piece of code!

  11. Xtyan says:

    Hi, i have this:

    Source File:
    \\edtnas2\web\Dev\Net2\iCapt\request\Cot.aspx.cs
    Line:

    how can I get the text between “b” tags?

    thx!

  12. leojg says:

    Thanks!

  13. ktor says:

    in some cases, a trim would be needed:

    jQuery.fn.justtext = function() {
       
        return $.trim($(this)  .clone()
                .children()
                .remove()
                .end()
                .text());
     
    };

  14. Amit says:

    Nyc tutorial

  15. Fonkie says:

    How do you solve this question?

    <ul id="panel">
    <li>
    <input  type="checkbox"  value="1" />one
    </li>
    </ul>
     


    I don’t want to remove the input element, I just want to replace the text “one” to “first”. This is my solution using jquery:

    var ele=$("#panel").find("li:eq(0)");
    var inputEle=ele.find("input");
    ele.text("first");
    ele.prepend(inputEle);
     


    Do you have a better solution?

  16. I am getting selcted text on Click but unable to get text of list box on Enter key press

    $('#listEQ li').live('click', function() {        
                    var selected = $(this).text();              
                    $("#ajax_response_smart").remove(); 
                    if (selected != "") {
                        var scripcode = selected.split("|");
                        document.getElementById('ctl00_ContentPlaceHolder1_smartSearch').value = scripcode[0];
                        document.getElementById('ctl00_ContentPlaceHolder1_hdnCode').value = scripcode[2];                    
                    }
                });
    

  17. MajiD says:

    Thanks, very useful snippet to get rid of the inner HTML and get the text only.

  18. sachin says:

    nice tutorial , please send link for learn jquery , javascript..

  19. Sharon says:

    Thanks Viral..this helps me finish half of my Job..But how can i change the text we got and assign the updated text?

    My aim is to get the text of div check for a word replace it and assogn back :-(

  20. Edoardo says:

    THANK YOU VERY VERY MUCH!

  21. sln says:

    thank you so much, I’ve been looking everywhere for this solution finally I got it here thanks.

  22. Brandon says:

    Hi great article.

    Is it possible to remove the text justtext() found?

    $(‘blah:contains(‘foo’)”).justtext().remove(); <— Doesn't work btw

  23. Kevin says:

    Here is my Version of the function as a getter and setter function:

    $.fn.justtext = function(newText) {
            var $children = null;
            
            if(newText) {
                $children = $(this)
                                .children()
                                .clone();
                
                $(this)
                    .children()
                    .remove()
                    .end()
                    .text(newText)
                    .prepend($children);
        
                return $(this);
            }
            else {
                return $.trim($(this)
                                  .clone()
                                  .children()
                                  .remove()
                                  .end()
                                  .text());
            }
        };
    

  24. Alice says:

    FYI, you got the typing phrase wrong. The phrase is meant to use every letter in the alphabet. “A quick brown fox jumps over a lazy dog” is incorrect because it doesn’t contain the letters t or h. The actual phrase is “The quick brown fox jumps over the lazy dog.” Count them, they’re all there.

  25. bruce says:

    hi,

    test

    how can i update the text inside the grandchild element without removing the child element only using parent element tag.
    So $(‘#parent’).text(‘new text’), it will remove the child and grand child. as i don’t care how many child and grand children parent has. i just want to update the most embedded text with parent tag, is it possible.

Leave a Reply

Your email address will not be published. Required fields are marked *