1

<a href="#">Domain name<span class="value">2</span></a>

I would like to retrieve only the text "Domain name".

I have tried using $('a').text() but that will also get the text inside the descending SPAN tag. Is there a way to select only the first text node inside the A tag somehow?

I can't figure out how.

.contents('not:(span)') do not work either.

bobmoff
  • 2,415
  • 3
  • 25
  • 32

3 Answers3

1

You could just use DOM methods:

var el = document.getElementById("your_element_id");
var child, textBits = [];
for (var i = 0; i < el.childNodes.length; ++i) {
    child = el.childNodes[i];
    if (child.nodeType == 3) {
        textBits.push(child.nodeValue);
    }
}
window.alert( textBits.join("") );
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Thanks, I tried your way and it worked. I refined it as I know its the first childnode. `.get(0).firstChild.nodeValue;` – bobmoff Feb 26 '10 at 17:20
0

I found a way!

$('a').get(0).firstElementChild.firstChild.wholeText;

bobmoff
  • 2,415
  • 3
  • 25
  • 32
0

Based on my answer to this question, this should work for you. this.nodeType == 3 determines that it's a text node. Currently this will get the text of all text nodes (but will work for your example). If you have text nodes after your span, you'd have to amend this to get only the first one.

var text = $('a') 
    .contents() 
    .filter(function() { 
        return this.nodeType == 3;
        //return this.nodeType == Node.TEXT_NODE;  this works unless using IE 7
    })
    .text(); 
Community
  • 1
  • 1
rosscj2533
  • 9,195
  • 7
  • 39
  • 56