Mahedi Sabuj
Mahedi Sabuj

Reputation: 2944

Get Inner Text from DIV

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?

Upvotes: 6

Views: 29941

Answers (6)

Andy Donegan
Andy Donegan

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

Pawan Nogariya
Pawan Nogariya

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

Fiddle

Upvotes: 2

DenseCrab
DenseCrab

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

Jamiec
Jamiec

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

John R
John R

Reputation: 2791

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

Upvotes: 1

Rosh Donniet
Rosh Donniet

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

Related Questions