torayeff
torayeff

Reputation: 9702

Jquery .text() function behaviour

I have this html snippet:

<div clas="some-div">
  <span class="same-class">text 1</span>
  <span class="same-class">text 2</span>
</div>

I want to extract text1 and text2 into two different variables.

var allText = $('.same-class').text(); //gives text 1text2
var t1 = $('.same-class')[0].text(); //gives error

How does .text() function behave?

Upvotes: 2

Views: 37

Answers (3)

Igor Bukin
Igor Bukin

Reputation: 1006

Description for the text(), from the jQuery doc:

Description: Get the combined text contents of each element in the set of matched elements, including their descendants.

Since the jQuery object $('.same-class') contains several elements, it combines text from all the elements into a single line.

In order to get a particular element text use: the .eq()

$('.same-class').eq(0).text();

method

Upvotes: 2

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

you could use $.each() as well, like:

var textArr = []; //array to store text
$('.same-class').each(function(idx, val) {
    textArr.push($(this).text());
});
console.log(textArr);

Upvotes: 3

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You have to use .eq() for this purpose,

var t1 = $('.same-class').eq(0).text(); 

If you use bracket notation to access the elements based on its index, then that will return a plain node object. And that will not contain a function called text in its prototype.

If you still want to use bracket notation, then do,

var t1 = $('.same-class')[0].textContent; 

Upvotes: 5

Related Questions