Get All Elements in an HTML document with a specific CSS Class

前端 未结 10 924
时光取名叫无心
时光取名叫无心 2020-12-01 04:10

What\'s the best way to get an array of all elements in an html document with a specific CSS class using javascript?

No javascript frameworks like jQuery allowed her

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 04:43

    The below answer is now pushing four years old, so it's worth noting that native browser support for getElementsByClassName() has gotten a lot better. But if you must support older browsers, then...

    Use one that's already been written. Most major JS libraries include one in some form or another, but if you aren't using one of them then i can recommend Robert Nyman's excellent implementation:

    http://code.google.com/p/getelementsbyclassname/
    http://www.robertnyman.com/2008/05/27/the-ultimate-getelementsbyclassname-anno-2008/

    There are just too many ways to make this (conceptually-simple) routine slow and buggy to justify writing your own implementation at this point.

提交回复
热议问题