0

I am trying to access the text of the first "th" element of the first element of "rows" with jQuery and would like to do so in one line

var currentStation = $(rows[0]).find("th")[0].text();

What would be the correct syntax to do so? I am able to get the "th" element, but as soon as I try to access the text I get error messages. I already tried numerous variations of different brackets combinations, but each one threw me errors.

9
  • 3
    show your html? Commented Aug 29, 2019 at 9:08
  • 3
    It's beecause you're using [0] at the end - this accesses the element, not the jQuery object, which is why .text() will no longer work as that's for jQuery only. Replacing .text() with .innerText should work. Commented Aug 29, 2019 at 9:09
  • please provide details code Commented Aug 29, 2019 at 9:10
  • what's wrong with var text = rows[0].cells[0].innerText; ? Commented Aug 29, 2019 at 9:10
  • 1
    @user7290573 Thanks! I think that boils down to the exact problem I had so far working with jQuery. I have neve made a clear distinction between jQuery objects and elements. You helped me a lot, thanks! Commented Aug 29, 2019 at 9:22

2 Answers 2

3

The issue is that your [0] on find("th") takes the HTML element out of the jQuery object. The easiest way to do this is to either use innerText instead of text:

var currentStation = $(rows[0]).find("th")[0].innerText;

Or don't use [0], rather first:

var currentStation = $(rows[0]).find("th:first").text();

(Or another first):

var currentStation = $(rows[0]).find("th").first().text();
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, was just about to add that @freedomn-m :p
Or yet another: .eq(0)
1

text() is a method on jQuery objects.

You are extracting the DOM element object from the jQuery object and then trying to call text() on the DOM element object.

Use the :first selector instead (note this is a jQuery selector and not a CSS selector)

const $firstRow = $(rows[0]);
const $firstTh = $firstRow.find("th:first");
var currentStation = $firstTh.text();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.