[英]How do I retrieve the textnode of a element without getting descending elements textnodes using Jquery?
<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. 我试过使用$('a')。text(),但这也会使文本降序进入SPAN标记。 Is there a way to select only the first text node inside the A tag somehow? 有没有办法以某种方式仅选择A标记内的第一个文本节点?
I can't figure out how. 我不知道怎么办。
.contents('not:(span)') do not work either. .contents('not:(span)')也不起作用。
You could just use DOM methods: 您可以只使用DOM方法:
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("") );
我找到了一个方法!
$('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. this.nodeType == 3确定它是一个文本节点。 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.