[javascript] How to get elements with multiple classes

Say I have this:

<div class="class1 class2"></div>

How do I select this div element?

document.getElementsByClassName('class1')[0].getElementsByClassName('class2')[0]

That does not work.

I know that, in jQuery, it is $('.class1.class2'), but I'd like to select it with vanilla JavaScript.

This question is related to javascript class element

The answer is


Okay this code does exactly what you need:

HTML:

<div class="class1">nothing happens hear.</div>

<div class="class1 class2">This element will receive yout code.</div>

<div class="class1">nothing happens hear.</div>

JS:

function getElementMultipleClasses() {
    var x = document.getElementsByClassName("class1 class2");
    x[0].innerHTML = "This is the element you want";
}
getElementMultipleClasses();

Hope it helps! ;)


querySelectorAll with standard class selectors also works for this.

document.querySelectorAll('.class1.class2');

AND (both classes)

var list = document.getElementsByClassName("class1 class2");
var list = document.querySelectorAll(".class1.class2");

OR (at least one class)

var list = document.querySelectorAll(".class1,.class2");

XOR (one class but not the other)

var list = document.querySelectorAll(".class1:not(.class2),.class2:not(.class1)");

NAND (not both classes)

var list = document.querySelectorAll(":not(.class1),:not(.class2)");

NOR (not any of the two classes)

var list = document.querySelectorAll(":not(.class1):not(.class2)");

html

<h2 class="example example2">A heading with class="example"</h2>

javascritp code

var element = document.querySelectorAll(".example.example2");
element.style.backgroundColor = "green";

The querySelectorAll() method returns all elements in the document that matches a specified CSS selector(s), as a static NodeList object.

The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

also learn more about https://www.w3schools.com/jsref/met_document_queryselectorall.asp

== Thank You ==


actually @bazzlebrush 's answer and @filoxo 's comment helped me a lot.

I needed to find the elements where the class could be "zA yO" OR "zA zE"

Using jquery I first select the parent of the desired elements:

(a div with class starting with 'abc' and style != 'display:none')

var tom = $('div[class^="abc"][style!="display: none;"]')[0];                   

then the desired children of that element:

var ax = tom.querySelectorAll('.zA.yO, .zA.zE');

works perfectly! note you don't have to do document.querySelector you can as above pass in a pre-selected object.


It's actually very similar to jQuery:

document.getElementsByClassName('class1 class2')

MDN Doc getElementsByClassName


As @filoxo said, you can use document.querySelectorAll.

If you know that there is only one element with the class you are looking for, or you are interested only in the first one, you can use:

document.querySelector('.class1.class2');

BTW, while .class1.class2 indicates an element with both classes, .class1 .class2 (notice the whitespace) indicates an hierarchy - and element with class class2 which is inside en element with class class1:

<div class='class1'>
  <div>
    <div class='class2'>
      :
      :

And if you want to force retrieving a direct child, use > sign (.class1 > .class2):

<div class='class1'>
  <div class='class2'>
    :
    :

For entire information about selectors:
https://www.w3schools.com/jquery/jquery_ref_selectors.asp


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to class

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes?

Examples related to element

How can I loop through enum values for display in radio buttons? How to count items in JSON data Access multiple elements of list knowing their index Getting Index of an item in an arraylist; Octave/Matlab: Adding new elements to a vector add item in array list of android GetElementByID - Multiple IDs Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence? Check if one list contains element from the other How to get the focused element with jQuery?