提问者:小点点

使用。text()仅检索未嵌套在子标记中的文本


如果我有这样的html:

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

我试图使用.text()来检索字符串“This is some text”,但是如果我说$('#list-item').text(),我会得到“This is some textFirst span textSecond span text”。

有没有一种方法可以只获取标记中的自由文本,而不获取其子标记中的文本(或者可能通过.text("“))来删除这些文本?

HTML不是我写的,所以这是我必须使用的。 我知道在编写html时将文本包装在标签中是很简单的,但同样,html是预先编写的。


共3个答案

匿名用户

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

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

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

匿名用户

简单的回答:

$("#listItem").contents().filter(function(){ 
  return this.nodeType == 3; 
})[0].nodeValue = "The text you want to replace with" 

匿名用户

在我看来,这似乎是一个过度使用jquery的案例。 下面将获取文本,忽略其他节点:

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

你需要修剪一下,但它能让你在一条简单的线上得到你想要的东西。

编辑

以上将获得文本节点。 要获取实际文本,请使用以下命令:

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