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
5 Answers
Reset to default 5try 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();//