简体   繁体   中英

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.

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();

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM