2014-02-26 130 views
1

我有這個演示,並嘗試獲取div的文本。
獲取div的文本不跨度

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

格看起來像

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

輸出: -

this is span 

,並希望new line

回答

4

嘗試這樣

如果DIV有一個id FOO或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

只實現這樣的:

var anchors = $('<div/>').append(string).text();//find() is removed as it will find the text not html span. 
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" 
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();// 
1

這應該找到一個div中的所有文本節點(用正確的選擇)

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