-2

In Chrome's developer console. I'm trying to grab a piece of text from a website.

Example:

<div class="someClass">This is some text!</div>

I expected this to work, but it returns 'undefined'

$('.someClass')[0].text

Yet that does work when the text is inside a tag with the same class. Is there something special occurring when the text is just inside a div? Thanks!

Erik Philips
  • 51,408
  • 11
  • 123
  • 146

3 Answers3

1

This $('.someClass')[0] returns a DOM element and not a jQuery object.

So, what you could use instead is $('.someClass')[0].textContent

freedomn-m
  • 24,983
  • 7
  • 32
  • 55
Ele
  • 32,412
  • 7
  • 33
  • 72
1

Problem you have is you are using brackets to reference the first element. With jQuery, that returns the DOM node and DOM does not have a text property.

You need to use .eq(0) to reference jQuery and it is a method so it would need parenthesis.

console.log($('.someClass').eq(0).text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="someClass">This is some text!</div>
epascarello
  • 195,511
  • 20
  • 184
  • 225
  • This solves my problem, AND clears up my confusion between DOM nodes and Javascript objects. Thanks epascarello! – jesse_2567 Oct 18 '18 at 23:44
0

This:

$('.someClass')

...returns a jQuery selection. You can get the text from that with:

$('.someClass').text()

However, if there is more than one .someClass, you'll get the text of all of those items. That may be why you have:

$('.someClass')[0]

...but that is no-longer a jQuery selection but is a DOM element which has neither a .text() method or a .text property. There is an innerText or textContent property, neither of which has wide browser support, so maybe you're best off doing:

$('.someClass').first().text()
Jacob
  • 75,331
  • 23
  • 142
  • 223