<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 th开发者_开发百科at 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.
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("") );
I found a way!
$('a').get(0).firstElementChild.firstChild.wholeText;
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();
精彩评论