ohana
ohana

Reputation: 285

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.

Upvotes: 0

Views: 1346

Answers (3)

M&#225;r &#214;rlygsson
M&#225;r &#214;rlygsson

Reputation: 14606

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. :-)

Upvotes: 2

Corey Sunwold
Corey Sunwold

Reputation: 10254

var tableContents = $(".myTable").text();

Just tested and this does work. Example page:

<html>
<head>
<script type="text/javascript" language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    alert($(".myTable").text()); 
});
</script>
</head>
<body>

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

Upvotes: 0

Shaz
Shaz

Reputation: 15877

$(".myTable").html().replace(/<span.*<\/span>/gi, "")

Example here: http://fiddle.jshell.net/TSYQJ/

Upvotes: 1

Related Questions