得到div的文本不跨越

时间:2014-02-26 08:23:07

标签: 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>

div看起来像

<div>
   <span>this is span</span>
   new line
</div>

输出: -

this is span

并希望new line

5 个答案:

答案 0 :(得分:4)

试试这个

如果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();

可选地

$("#foo").contents()
.filter(function() {
  return this.nodeType === 3;
}).text()

DemoFiddle

答案 1 :(得分:1)

按照以下方式实施:

var anchors = $('<div/>').append(string).text();//find() is removed as it will find the text not html span.

答案 2 :(得分:1)

这应该找到div中的所有文本节点(使用右选择器)

console.log($('div').contents()
.filter(function() {
  return this.nodeType === 3;
}).text())

答案 3 :(得分:0)

Could use regex

JS:

var string = "<span>this is span</span>new line<a>I don't want this</a>";

// finds "<word>text</word>" and replaces with ""
string = string.replace(/<[a-zA-Z]+>[^(<\/)]*<\/[a-zA-Z]+>/g, function(){
  return "";
});

alert(string); // "new line"

答案 4 :(得分:0)

试试这个:

var string = "<span>this is span</span>new line";
var jdiv = $('<div/>');
var jspan = jdiv.append(string).find('span');
//get whatever you want
jspan.text();//
jdiv.text();//