How to get all elements by class name? [duplicate]

document.getElementsByClassName(klass)

Be aware that some engines (particularly the older browsers) don’t have it. You might consider using a shim, if that’s the case. It will be slow, and iterate over the whole document, but it will work.

EDIT several years later: You can get the same result using document.querySelectorAll('.klass'), which doesn’t seem like much, but the latter allows queries on any CSS selector, which makes it much more flexible, in case “get all elements by class name” is just a step in what you are really trying to do, and is the vanilla JS answer to jQuery’s $('.class').

Leave a Comment