获取div的文本而不是span

웃웃웃*_*웃웃웃 2 javascript jquery

我有这个演示并尝试获取 div 的文本。

<script>
var string = "<span>this is span</span>new line";
var anchors = $('<div/>').append(string).find('span').text();
console.log(anchors);
</script>
Run Code Online (Sandbox Code Playgroud)

div 看起来像

<div>
   <span>this is span</span>
   new line
</div>
Run Code Online (Sandbox Code Playgroud)

输出:-

this is span
Run Code Online (Sandbox Code Playgroud)

并想要new line

Vin*_*ngh 5

尝试这样

如果 div 有一个 id foo 或 class foo

$("#foo") //can not use div as will target all the divs
    .clone()    //clone the element
    .children() //select all the children
    .remove()   //remove all the children
    .end()  //again go back to selected element
    .text();
Run Code Online (Sandbox Code Playgroud)

或者

$("#foo").contents()
.filter(function() {
  return this.nodeType === 3;
}).text()
Run Code Online (Sandbox Code Playgroud)

演示小提琴