querySelectorAll()

a JavaScript function for selecting elements
  1. Welcome
  2. Examples
    - addEventListener()
    - Buttons
    - Data Attribute
    - document.
    querySelectorAll()

    - forEach()
    - Multiple Classes
    - to array
  3. Errors
    - Failed to execute 'querySelectorAll' on 'document'
  4. Advanced
  5. querySelectorAll() vs querySelector()
  6. Performance
  7. Troubleshooting

Links

  1. allowfullscreen
  2. Questions LLC

Multiple Classes

The querySelectorAll() function is a method of the Document object in JavaScript. It allows you to retrieve a list of elements that match a specified CSS selector. You can use it to find elements with multiple classes by using the .class1.class2 syntax.

Here is an example of how to use querySelectorAll() to find all elements with the classes "class1" and "class2":

const elements = document.querySelectorAll(".class1.class2");

In this example, elements will be a NodeList of all elements on the page that have both the "class1" and "class2" classes.

You can also use querySelectorAll() to find elements with multiple classes by chaining multiple class selectors together. For example, you can find all elements with the class "class1" or "class2" using the following code:

const elements = document.querySelectorAll(".class1, .class2");

In this example, elements will be a NodeList of all elements on the page that have either the "class1" or "class2" classes.

You can also use querySelectorAll() to find elements with multiple classes by chaining multiple class selectors together in the context of a parent element. Here is an example of how to find all elements with the classes "class1" and "class2" within a parent element with the id "parent-element":

const parent = document.getElementById("parent-element"); const elements = parent.querySelectorAll(".class1.class2");

In this example, elements will be a NodeList of all elements within the parent element with the id "parent-element" that have both the "class1" and "class2" classes.

Note that querySelectorAll() returns a NodeList, which is similar to an array but not quite the same. If you need to use array methods like forEach(), you can convert the NodeList to an array using the Array.from() method.

const elementsArray = Array.from(elements);

You can also use querySelectorAll() with attribute selectors to find elements with multiple classes or attributes. Here is an example of how to find all elements with class "class1" and attribute "data-example":

const elements = document.querySelectorAll(".class1[data-example]");

In this example, elements will be a NodeList of all elements on the page that have class "class1" and attribute "data-example".

In this way you can use querySelectorAll() function to find elements with multiple classes and attributes in a very efficient and flexible way.