Reputation: 79
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.
Upvotes: 0
Views: 64
Reputation: 44087
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();
Upvotes: 3
Reputation: 943214
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();
Upvotes: 1