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>

2
  • 1
    console.log($('.container .content').eq(0).text()); Commented Apr 13, 2016 at 12:14
  • 2
    $('.container .content')[0] - returns a dom element reference which does not have text() method Commented Apr 13, 2016 at 12:14

3 Answers 3

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());
Sign up to request clarification or add additional context in comments.

1 Comment

Or $('.container:first .content')
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>

2 Comments

'.container .content:first' will select first .content child from all .container parents right ?
yes, it will select only first one from all matched element
0

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

This will target just the first of type

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.