Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/421.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取div not span的文本_Javascript_Jquery - Fatal编程技术网

Javascript 获取div not span的文本

Javascript 获取div not span的文本,javascript,jquery,Javascript,Jquery,我有这个演示,并试图获得div的文本 想换一条新线路吗 如果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

我有这个演示,并试图获得div的文本

想换一条新线路吗

如果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()
像这样试试

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

就这样实现:

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

就这样实现:

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

JS:

试试这个:

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();//
试试这个:

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();//

这将使用右选择器查找div中的所有文本节点

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

这将使用右选择器查找div中的所有文本节点

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