最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - get the text of div not span - Stack Overflow

programmeradmin0浏览0评论

i have this demo and try to get the text of div.

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

div look like

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

output:-

this is span

and want to new line

i have this demo and try to get the text of div.

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

div look like

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

output:-

this is span

and want to new line

Share Improve this question asked Feb 26, 2014 at 8:23 웃웃웃웃웃웃웃웃웃웃 3623 gold badges17 silver badges32 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 5

try like this

if div had an id foo or 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();

Alternatively

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

DemoFiddle

Just implement like this:

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

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"

This should find all the text nodes in a div (with the right selector)

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

try this:

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();//
发布评论

评论列表(0)

  1. 暂无评论