如果我有这样的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是预先编写的。


当前回答

使用一个额外的条件来检查innerHTML和innerText是否相同。只有在这种情况下,才需要替换文本。

$(function() {
$('body *').each(function () {
    console.log($(this).html());
    console.log($(this).text());
    if($(this).text() === "Search" && $(this).html()===$(this).text())  {
        $(this).html("Find");
    }
})
})

http://jsfiddle.net/7RSGh/

其他回答

这对我来说是个好方法

   var text  =  $('#listItem').clone().children().remove().end().text();

对我来说,这似乎是一个过度使用jquery的例子。下面将抓取文本,忽略其他节点:

document.getElementById("listItem").childNodes[0];

你需要修剪它,但它能让你在一个简单的线条中得到你想要的。

EDIT

上面将获得文本节点。要得到实际的文本,使用这个:

document.getElementById("listItem").childNodes[0].nodeValue;

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

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

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

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

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

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

我喜欢这个基于clone()方法的可重用实现,它只获取父元素中的文本。

为方便参考而提供的代码:

$("#foo")
    .clone()    //clone the element
    .children() //select all the children
    .remove()   //remove all the children
    .end()  //again go back to selected element
    .text();

就像问题一样,我试图提取文本,以便对文本进行一些正则表达式替换,但在我的内部元素(即:< I >, <div>, <span>等)也被删除的地方出现问题。

下面的代码似乎工作得很好,解决了我的所有问题。

它使用这里提供的一些答案,但特别地,只会在元素为nodeType === 3时替换文本。

$(el).contents().each(function() { 
  console.log(" > Content: %s [%s]", this, (this.nodeType === 3));

  if (this.nodeType === 3) {
    var text = this.textContent;
    console.log(" > Old   : '%s'", text);

    regex = new RegExp("\\[\\[" + rule + "\\.val\\]\\]", "g");
    text = text.replace(regex, value);

    regex = new RegExp("\\[\\[" + rule + "\\.act\\]\\]", "g");
    text = text.replace(regex, actual);

    console.log(" > New   : '%s'", text);
    this.textContent = text;
  }
});

上面所做的是遍历给定el的所有元素(它是通过$("div.my-class[name='some-name']"获得的);对于每个内部元素,它基本上都会忽略它们。对于文本的每个部分(由if (this。nodeType === 3),它将只对这些元素应用regex替换。

这。textContent = text部分只是替换替换的文本,在我的情况下,我正在寻找像[[min.val]], [[max.]]这样的标记。val]]等。

这段简短的代码摘录将帮助任何人试图做什么问题是问…再多一点。