Reputation: 2944
HTML:
<div id="country">
<span>B</span>
Bangladesh
</div>
<div id="capital">
Dhaka
<span>D</span>
</div>
#country
, I want to get Bangladesh#capital
, I want to get DhakaHow can I achieve this?
Upvotes: 6
Views: 29941
Reputation: 915
answer = $('#capital').clone();
answer.children('span').remove();
alert(answer.text()); // alerts "text"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="country">
<span>B</span>
Bangladesh
</div>
<div id="capital">
Dhaka
<span>D</span>
</div>
Plenty of answers already.
You can use .clone() for that, like so:
answer = $('#capital').clone();
answer.children('span').remove();
alert(answer.text()); // alerts "text"
Using this format you can add other elements to your div and hopefully the code above is simple enough to be able to see how to remove them.
Original answer from : get text in div
Upvotes: 1
Reputation: 8960
Similar to Andy's answer, but this will remove all the elements so you do not have to do per child element removal, so no matter how many children or what structure is inside your div, it will always return the text
var clone = $('div#country').clone();
clone.find('*').remove();
console.log(clone.text());
Upvotes: 2
Reputation: 1313
Try if this works
$('#country').clone().children().remove().end().text();
$('#capital').clone().children().remove().end().text();
.clone()
clones the selected element.
.children()
selects the children from the cloned element
.remove()
removes the previously selected children
.end()
selects the selected element again
.text()
gets the text from the element without children
Upvotes: 12
Reputation: 136104
You can filter the contents
for text nodes (nodetype=3) and read the textContent
:
var country = $('#country').contents().filter(function() {
return this.nodeType == 3
})[1].textContent;
Upvotes: 1
Reputation: 2791
You can get that text by using nextSibling
and previousSibling
attribute.
Example:
$("#country").find("span")[0].nextSibling.nodeValue;
$("#capital").find("span")[0].previousSibling.nodeValue;
Upvotes: 1
Reputation: 418
Can't you just edit the HTML ?
<div id="country">
<span>B</span>
<span class="text">Bangladesh</span>
</div>
<div id="capital">
<span class="text">Dhaka</span>
<span>D</span>
</div>
Then, using jQuery :
var one = $("#country>.text").text();
var two = $("#capital>.text").text();
Upvotes: 3