如果我有这样的html:

<li id="listItem">
    This is some text
    <span id="firstSpan">First span text</span>
    <span id="secondSpan">Second span text</span>
</li>

我试图使用.text()检索字符串“这是一些文本”,但如果我说$('#list-item').text(),我得到“这是一些textFirst span textSecond span文本”。

是否有一种方法可以获取(并可能通过.text("")之类的方法删除)标签中的自由文本,而不是其子标签中的文本?

HTML不是我写的,所以这是我必须与工作。我知道这将是简单的,只是包装标签的文本时编写的html,但再次,html是预先编写的。


当前回答

我建议使用createTreeWalker来查找所有没有附加到html元素的文本元素(这个函数可以用来扩展jQuery):

function textNodesOnlyUnder(el) { var resultSet = []; var n = null; var treeWalker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, function (node) { if (node.parentNode.id == el.id && node.textContent.trim().length != 0) { return NodeFilter.FILTER_ACCEPT; } return NodeFilter.FILTER_SKIP; }, false); while (n = treeWalker.nextNode()) { resultSet.push(n); } return resultSet; } window.onload = function() { var ele = document.getElementById('listItem'); var textNodesOnly = textNodesOnlyUnder(ele); var resultingText = textNodesOnly.map(function(val, index, arr) { return 'Text element N. ' + index + ' --> ' + val.textContent.trim(); }).join('\n'); document.getElementById('txtArea').value = resultingText; } <li id="listItem"> This is some text <span id="firstSpan">First span text</span> <span id="secondSpan">Second span text</span> </li> <textarea id="txtArea" style="width: 400px;height: 200px;"></textarea>

其他回答

使用简单的JavaScript在IE 9+兼容语法在短短几行:

const childNodes = document.querySelector('#listItem').childNodes;

if (childNodes.length > 0) {
    childNodesLoop:
    for (let i = 0; i < childNodes.length; i++) {
        //only target text nodes (nodeType of 3)
        if (childNodes[i].nodeType === 3) {
            //do not target any whitespace in the HTML
            if (childNodes[i].nodeValue.trim().length > 0) {
                childNodes[i].nodeValue = 'Replacement text';
                //optimized to break out of the loop once primary text node found
                break childNodesLoop;
            }
        }
    }
}

对于初学者来说:

我更喜欢@都尊的答案,因为它简单易懂,比公认的答案更有效率。但它只部分适用于我,因为你不能直接传递元素与类选择器像这样

$(".landing-center .articlelanding_detail").get(0).immediateText() //gives .immediateText is not a function error

或者这个

$(".landing-center .articlelanding_detail")[0].immediateText() //gives .immediateText is not a function error

因为一旦你从$()函数中使用[index]或.get(index)提取了原生元素,你就失去了这里提到的jQuery对象方法的可链性。大多数解决方案只在id的上下文中使用,对于带有类选择器的元素多次使用不是很优雅。

所以,我写了jQuery插件:

$.fn.mainText = function(x=0) {
    return $.trim(this.eq(x).contents().not(this.eq(x).children()).text().replace(/[\t\n]+/g,' '));
};

这将返回元素的文本,而不管是否使用id或class作为排除子元素的选择器。也将删除任何\t或\n以获得一个干净的字符串。 像这样使用它:

案例1

$("#example").mainText(); // get the text of element with example id

案例2

$(".example").mainText(); // get the text of first element with example class

案例3

$(".example").mainText(1); // get the text of second element with example class and so on..

试试这个:

$('#listItem').not($('#listItem').children()).text()

我不会为此而使用jQuery,尤其是那些对元素进行不必要克隆的解决方案。您所需要的就是一个简单的循环抓取文本节点。在现代JavaScript中(在撰写本文时,“现代”是一个移动的目标!),并从结果的开头和结尾删除空白:

const { childNodes } = document.getElementById("listItem");
let text = "";
for (const node of childNodes) {
    if (node.nodeType === Node.TEXT_NODE) {
        text += node.nodeValue;
    }
}
text = text.trim();

生活例子:

const {childNodes} = document.getElementById("listItem"); Let text = ""; (childNodes的const节点){ 如果节点。nodeType === Node.TEXT_NODE) { text += node.nodeValue; } } console.log(文本); <李id = "列" > 这是一些文本 <span id="firstSpan">第一个span文本</span> <span id="secondSpan">Second span text</span> . <span id="secondSpan"> 李< / >

有些人会用reduce来表示。我不是一个粉丝,我认为一个简单的循环更清楚,但这种用法确实在每次迭代时更新累加器,所以它实际上并没有滥用reduce:

const { childNodes } = document.getElementById("listItem");
const text = [...childNodes].reduce((text, node) =>
    node.nodeType === Node.TEXT_NODE ? text + node.nodeValue : text
, "").trim();

const {childNodes} = document.getElementById("listItem"); const text =[…childNodes]。Reduce ((text, node) => 节点。nodeType ===节点。TEXT_NODE吗?文本+节点。nodeValue:文本 ”、“).trim (); console.log(文本); <李id = "列" > 这是一些文本 <span id="firstSpan">第一个span文本</span> <span id="secondSpan">Second span text</span> . <span id="secondSpan"> 李< / >

或者不创建临时数组:

const { childNodes } = document.getElementById("listItem");
const text = Array.prototype.reduce.call(childNodes, (text, node) =>
    node.nodeType === Node.TEXT_NODE ? text + node.nodeValue : text
, "").trim();

const {childNodes} = document.getElementById("listItem"); const text = Array.prototype.reduce。call(childNodes, (text, node) => 节点。nodeType ===节点。TEXT_NODE吗?文本+节点。nodeValue:文本 ”、“).trim (); console.log(文本); <李id = "列" > 这是一些文本 <span id="firstSpan">第一个span文本</span> <span id="secondSpan">Second span text</span> . <span id="secondSpan"> 李< / >

类似于公认的答案,但没有克隆:

$("#foo").contents().not($("#foo").children()).text();

下面是一个jQuery插件用于此目的:

$.fn.immediateText = function() {
    return this.contents().not(this.children()).text();
};

下面是如何使用这个插件:

$("#foo").immediateText(); // get the text without children