Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementsByClassName() with two classes

Is it possible to get all elements with class a or b using getElementsByClassName() only once? I'd prefer vanilla JavaScript.

like image 245
Unknown developer Avatar asked May 16 '16 13:05

Unknown developer


People also ask

Can we use two classes in same element?

Multiple classes can be applied to a single element in HTML and they can be styled using CSS.

What is getElementsByClassName () used for?

The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s). When called on the document object, the complete document is searched, including the root node.

Can a div tag have multiple classes?

Absolutely, divs can have more than one class and with some Bootstrap components you'll often need to have multiple classes for them to function as you want them to. Applying multiple classes of course is possible outside of bootstrap as well.

What is the use of getElementsByClassName?

Definition and Usage. The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.

How to get elements by multiple class names in HTML?

Use the getElementsByClassName method to get elements by multiple class names, e.g. document.getElementsByClassName ('box green'). The method returns an array-like object containing all of the elements which have all of the given class names. Here is the HTML for the examples in this article. Copied! And here is the related JavaScript code. Copied!

What is the difference between the getElementsByClassName () and the nodelist () methods?

The getElementsByClassName () method returns a collection of child elements with a given class name. The getElementsByClassName () method returns a NodeList object. A NodeList is an array-like collection (list) of Node Objects. A NodeList has a length property that returns the number of nodes in the list. The nodes can be accessed by index numbers.

How to get the matching elements of a class in JavaScript?

Same way we also fetch the matching elements which are of the class “test” and printing the same in the output. Then by this function “document.getElementsByClassName (‘test’) [0]” we retrieve the first element belonging to the class “test”. It returns undefined when there is no matching element.


1 Answers

You can't do it with getElementsByClassName() method instead use querySelectorAll() method with comma separated class selectors.

document.querySelectorAll('.a,.b') 
like image 147
Pranav C Balan Avatar answered Sep 23 '22 06:09

Pranav C Balan