wharfdale
wharfdale

Reputation: 752

Javascript contains - checking multiple values

I have just noticed my .contains was not working when I had multiple values (comma separated).

var checkMenu = document.getElementById('primary-header');
var primaryHeaderClasses = checkMenu.classList;

switch( true ) {
case primaryHeaderClasses.contains('primary-header--center-logo-center-menu, primary-header--left-logo-secondary-menu'):

If I remove the second class in the contains, it works fine:

switch( true ) {
case primaryHeaderClasses.contains('primary-header--center-logo-center-menu'):

What's the correct method to do the .contains to check for one or more classes?

Upvotes: 0

Views: 906

Answers (3)

wasanga7
wasanga7

Reputation: 242

If you're looking to do X if either class is present, why don't you do this?

if(primaryHeaderClasses.contains('primary-header--center-logo-center-menu') || primaryHeaderClasses.contains('primary-header--left-logo-secondary-menu')) {
    // Do stuff
}

By adding || you are telling "if this or this is true, do X".

If you have a good level at JQuery and JavaScript you can use this form:

if($("document:contains('primary-header--center-logo-center-menu'), document:contains('primary-header--left-logo-secondary-menu')")) {
    // Do stuff
}

Upvotes: 2

Antonis Koursoumis
Antonis Koursoumis

Reputation: 91

You can use .some() to do this.

Essentially what .some() does is that it checks every element of the array using a function and if any element returns true then it returns true. Otherwise, it returns false.

In your case you want to use

['primary-header--center-logo-center-menu', 'primary-header--left-logo-secondary-menu'].some(e => primaryheaderClasses.contains(e))

and this will only return true if primaryHeaderClasses contains any element e of the array.

This also works in all browsers (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)

Upvotes: 0

Jasper
Jasper

Reputation: 71

Contains does not support multiple values, you should make a loop and check the values for each entry. As far as I know this is the only way you could do this.

Upvotes: 0

Related Questions