Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Inner Text from DIV

Tags:

jquery

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?

like image 671
Mahedi Sabuj Avatar asked May 18 '16 12:05

Mahedi Sabuj


People also ask

How do I get text inside a div using jQuery?

To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents.

How do I get innerText in HTML?

The html(), text(), and val() are the most useful methods that can be utilized to get and set the inner text of HTML elements in jQuery. text() method gets and sets the content of HTML elements whereas, the html() method also sets its HTML markup.

How do I access a tag within a div?

The Div Object in HTML DOM is used to represent the HTML <div> element. This tag is used to specify the container for other HTML elements to style them with CSS or to perform certain tasks with JavaScript. Syntax: The <div> element can be accessed by using getElementById() method.


1 Answers

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

like image 97
DenseCrab Avatar answered Oct 03 '22 17:10

DenseCrab