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


当前回答

如果文本节点的位置索引在其兄弟节点中是固定的,则可以使用

$('parentselector').contents().eq(index).text()

其他回答

这对我来说是个好方法

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

为了能够修剪结果,像这样使用DotNetWala's:

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

我发现使用较短的版本,如document.getElementById(“listItem”)。childNodes[0]不能使用jQuery的trim()。

如果文本节点的位置索引在其兄弟节点中是固定的,则可以使用

$('parentselector').contents().eq(index).text()

我喜欢这个基于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').not('span').text();

http://api.jquery.com/not/