Search code examples
jquerydomtextnodenodevalue

how to read string only and ignore other element in JQuery


I have the following 'td'element, and want to read out the string part (cell 1) ONLY without the 'span' part, how can i do that in jQuery?

<td class="myTable">cell 1<span class='end'>&emsp;</span></td>

Thanks.


Solution

  • Here's a generic solution that will do it without ugly RegExp nastiness :-)

    var text = $('.myTable').clone()
                  .children()
                      .detach()
                  .end()
                  .text();
    

    Edit 1:
    Alternatively, if you're certain that the <span> will always only include some sort of a space character - you could use .text() followed by a .trim(), like so:

    $.trim( $('.myTable').text() );
    

    Edit 2:
    Just to play some more, here's another take on a generic solution that doesn't involve jQuery much, and is therefore much more efficient. I present the awesome .readStringOnly() plugin:

    $.fn.readStringOnly = function () {
        var nodes = this[0].childNodes,
            text = '';
        for (var i=0, item; (item = nodes[i]); i++) {
          if ( item.nodeType == 3 ) { // text node! 
            text += item.nodeValue;
          }
        }
        return text;
      };
    
    // Usage:
    //   var text = $('.myTable').readStringOnly();
    

    This is essentially what the first solution does in pure jQuery methods, but since jQuery provides no support for text-node handling one is left with two fairly bad options: inefficient jQuery code, or this sort of bulky W3C-DOM fugliness. (just as good I made a plugin out of it.)

    ...

    Then again, you could always just use a regular expression as suggested by someone already. :-)