Reputation: 1791
How do i extract the text part of a div leaving out text of inner html tags
Here is the div
<div class="MessageBox">I want to see only this message<span....>Click Here to collapse</span></div>
Here is the jquery inside a javascript function
var message= $(".MessageBox").text();
Right now i am getting message= "I want to see only this message Click Here to collapse"
I want message ="I want to see only this message"
Upvotes: 2
Views: 2382
Reputation: 2063
Sure, you could do something like this:
div = $('.MessageBox').clone();
inner = div.children();
inner.remove();
alert(div.text());
Upvotes: 0
Reputation: 318162
You can filter the selector for nodetypes that are text only (exclude elements), and get the text like so:
var text = $('.MessageBox').contents().filter(function() {
return this.nodeType == 3;
}).text();
Upvotes: 2
Reputation: 207861
Try:
$('.MessageBox')
.clone() //clones the element
.children() //selects all the children
.remove() //removes all the children
.end() //again goes back to selected element
.text(); //gets the text of element
Upvotes: 1
Reputation: 17553
You can use the clone()
method to clone the main element, then remove the children of that clone in order to discard the parts you don't want:
var clone = $('.MessageBox').clone();
clone.children().remove();
var message = clone.text();
You could, of course, skip the cloning part. But then you'd actually be removing the elements from the page, and I'm not sure that you want to do that. Cloning the main element allows you to then manipulate a copy of it, rather than the one the user actually sees.
Upvotes: 3