简体   繁体   English

如何使用Jquery检索元素的textnode而不获取降序元素的textnodes?

[英]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.

相关问题 使用jQuery拆分包含TextNodes和元素的元素 - Split an element containing TextNodes and elements using jQuery 如何使用JavaScript将文本节点中的纯文本图像URL替换为img元素? - How do I replace plain text image URLs in textnodes with img elements using JavaScript? 如何获取js元素中存在的任何位置的textnodes - How can I get textnodes of any position present in element in js 如何使用jQuery在每次单击时从特定元素中以倒序(降序)选择“ n”个连续元素? - How to select 'n' consecutive elements from specific element in reverse(descending) order on every click using jQuery? 如何使用JQuery循环表元素和检索数据元素? - How do I loop through table elements AND retrieve data elements using JQuery? 使用jQuery包装unwrapped textNode - Wrap unwrapped textNode using jQuery 使用jQuery检查体内是否有任何textNode - Checking if there is any textNodes in body using jquery 如何隐藏与没有jQuery时单击的元素最接近的元素? - How do I hide the closest element to the element that was clicked without jQuery? 如何使用$ .post()将Jquery变量发送到我的views.py,以及如何在不刷新页面的情况下检索它们 - How do I send Jquery variable to my views.py using $.post(), and how do i retrieve them without refreshing the page 如何在单击元素时切换类,但使用 JQuery 从所有其他元素中删除相同的类? - How do I toggle a class on click of an element but remove the same class from all other elements using JQuery?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM