0

I can do something like this:

console.log($('.container .content').text());

But I cannot do something like this:

console.log($('.container .content')[0].text());

I got a TypeError: $(...)[0].text is not a function. Why does this happen? How can I get the text of the first element in the selected jquery array?

SNIPPET:

console.log($('.container .content').text());
<div class="container">
  <p class="content">
    Contents
  </p>
</div>
<div class="container">
  <p class="content">
    Contents
  </p>
</div>
Searene
  • 25,920
  • 39
  • 129
  • 186

3 Answers3

3

$('.container .content')[0] returns a DOM object, you can't use jQuery methods like .text() on it.

Instead use console.log($('.container .content').eq(0).text());

OR

console.log($($('.container .content')[0]).text());// wrap jQuery wrapper and then use jQuery method `.text()`

OR(use jQuery .first()).

console.log($('.container .content').first().text());
Kartikeya Khosla
  • 18,743
  • 8
  • 43
  • 69
1

Try this : You are using index [0] to the jquery object which returns javascript object and then calling .text() which won't work as this is a jquery method and not javascript method.

Either you can use :first if you target to have text of first matched element as shown below

console.log($('.container .content:first').text());

or user :eq() for desired index object

console.log($('.container .content:eq(0)').text());

Demo:

alert($('.container .content:first').text());
alert($('.container .content').first().text());
alert($('.container .content:eq(0)').text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <p class="content">
    Contents1
  </p>
</div>
<div class="container">
  <p class="content">
    Contents2
  </p>
</div>
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
0

console.log($('.container .content').first().text());

This will target just the first of type

Sonny Prince
  • 1,094
  • 7
  • 15