6

HTML:

<div id="country">
    <span>B</span>
    Bangladesh
</div>

<div id="capital">
    Dhaka
    <span>D</span>
</div>
  1. From #country, I want to get Bangladesh
  2. From #capital, I want to get Dhaka

How can I achieve this?

f_puras
  • 2,521
  • 4
  • 33
  • 38
Mahedi Sabuj
  • 2,894
  • 3
  • 14
  • 27
  • Thisis for replacing the text - but the process of getting it is included in the answers: http://stackoverflow.com/questions/11867269/replace-only-text-inside-a-div-using-jquery – Jamiec May 18 '16 at 12:17
  • https://jsfiddle.net/xzc6m6ju/1/ – Zubair sadiq May 18 '16 at 12:28

6 Answers6

12

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

DenseCrab
  • 1,273
  • 11
  • 22
3

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();
Rosh Donniet
  • 418
  • 2
  • 10
2

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());

Fiddle

Pawan Nogariya
  • 8,330
  • 12
  • 52
  • 105
1

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;
Jamiec
  • 133,658
  • 13
  • 134
  • 193
1

You can get that text by using nextSibling and previousSiblingattribute.

Example:

$("#country").find("span")[0].nextSibling.nodeValue;
$("#capital").find("span")[0].previousSibling.nodeValue;

Fiddle Demo

John R
  • 2,741
  • 2
  • 13
  • 32
1

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

Community
  • 1
  • 1
Andy Donegan
  • 782
  • 1
  • 9
  • 30