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?
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;
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With