Richard Hamilton
Richard Hamilton

Reputation: 26434

JavaScript - How to get the text of the first child of a DOM element?

I am trying to build an array of fruits in JavaScript and to do so, I need to get text values of all li children of my ul element. I've made some good progress, in that I was able to find the number of children my list had.

$("#fruits-list > li").length
=> 6

I can also find elements by index. Here, I found the first element using this

$("#fruits-list > li")[0]
=> <li id="apple">Apple</li>

I'm able to get the element, but I'm unable to get the test value of it. Here, I'm trying to just get the text value apple, and I have tried just about everything. I've tried

  1. $("#fruits-list > li")[0].text
  2. $("#fruits-list > li")[0].html
  3. $("#fruits-list > li")[0].val

I got undefined for all three of them. I also tried adding () at the end of all of them, but got TypeError: Is not a function.

I could not find an answer here on SO. Any help is appreciated. Thanks in advance.

Upvotes: 0

Views: 1982

Answers (3)

aebabis
aebabis

Reputation: 3705

When you access $("#fruits-list > li")[0], you are getting an HTMLElement object, which is why you cannot use jQuery's function on it. dystroy's solution let's you use jQuery to get the text because eq returns an instance of jQuery. You can also do

$("#fruits-list > li")[0].textContent

Upvotes: 2

Sterling Archer
Sterling Archer

Reputation: 22395

text, html and val are not properties of the DOM, they are jQuery methods.

You could simply do a natural JS method.

document.querySelector("#fruits-list > li").textContent; //or innerText for legacy IE

querySelector returns the first item of a list of elements. (if you use jQuery, however, I suggest dystroy's answer)

Upvotes: 4

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

When you use the bracket notation with an index on a jQuery element, you get a DOM element. Those objects can't be called with jQuery functions directly. Use eq instead.

Use

$("#fruits-list > li").eq(0).text()

Note that if your end goal is to build an array of the texts of the LI elements, you can simply do

var arr = $("#fruits-list > li").map(function(){ return $(this).text() }).get();

Upvotes: 5

Related Questions