Is it possible to get all elements with class a
or b
using getElementsByClassName()
only once? I'd prefer vanilla JavaScript.
Multiple classes can be applied to a single element in HTML and they can be styled using CSS.
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.
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.
Definition and Usage. The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.
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!
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.
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.
You can't do it with getElementsByClassName()
method instead use querySelectorAll()
method with comma separated class selectors.
document.querySelectorAll('.a,.b')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With