最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to get the length of an ordered list? - Stack Overflow

matteradmin5PV0评论

Trying to convert some jQuery to javascript. Was using this for jQuery:

 var list = $('.list li'),
     listLength = list.length;

Now I'm trying it with JS, but it doesn't seem to work:

 var list = document.querySelector(".list"),
     listLi = list.getElementsByTagName("li"),
     listLength = listLi.length;

Any ideas?

Trying to convert some jQuery to javascript. Was using this for jQuery:

 var list = $('.list li'),
     listLength = list.length;

Now I'm trying it with JS, but it doesn't seem to work:

 var list = document.querySelector(".list"),
     listLi = list.getElementsByTagName("li"),
     listLength = listLi.length;

Any ideas?

Share Improve this question asked Jan 8, 2013 at 7:16 user1929705user1929705 211 silver badge8 bronze badges 3
  • 2 Works just fine for me - jsfiddle/gWvCQ – Andreas Commented Jan 8, 2013 at 7:20
  • 1 Your Vannila JS code works just fine. – Sandeep Commented Jan 8, 2013 at 7:22
  • 1 Yeah, thanks, just had a typo in the actual code. Oops! – user1929705 Commented Jan 8, 2013 at 7:25
Add a ment  | 

1 Answer 1

Reset to default 3

Your code should already work. But you can also use document.querySelectorAll() to perform a selector match which is cleaner than the two separate calls:

var listLi = document.querySelectorAll(".list li"),
    listLength = listLi.length;
Post a comment

comment list (0)

  1. No comments so far