Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery .text() function behaviour

Tags:

jquery

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?

like image 458
torayeff Avatar asked Sep 18 '26 21:09

torayeff


2 Answers

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; 
like image 157
Rajaprabhu Aravindasamy Avatar answered Sep 20 '26 10:09

Rajaprabhu Aravindasamy


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);
like image 23
Sudhir Bastakoti Avatar answered Sep 20 '26 11:09

Sudhir Bastakoti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!