Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 here right now, and I could loop all the elements and check them manually myself. I'm hoping for something a little more elegant.

like image 826
Joel Coehoorn Avatar asked Oct 16 '08 21:10

Joel Coehoorn


People also ask

Which document method obtains all HTML elements that implement a CSS class?

The querySelectorAll() method returns all elements that matches a CSS selector(s).

How do you get all elements with the same class?

We can get text from multiple elements with the same class in Selenium webdriver. We have to use find_elements_by_xpath(), find_elements_by_class_name() or find_elements_by_css_selector() method which returns a list of all matching elements.

How would you find all HTML elements on a page by class?

The getElementsByClassName() method returns a collection of elements with a specified class name(s). The getElementsByClassName() method returns an HTMLCollection. The getElementsByClassName() property is read-only.

How do you select all elements in a CSS class?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)


2 Answers

1) Get all elements in the document (document.getElementsByTagName('*'))
2) Do a regular expression match on the element's className attribute for each element

like image 125
Chris MacDonald Avatar answered Oct 02 '22 17:10

Chris MacDonald


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.

like image 39
Shog9 Avatar answered Oct 02 '22 16:10

Shog9