Skip to content Skip to sidebar Skip to footer

If Classlist Contains More Than One Specific Class

I need a function to trigger if the element recordplayerstick contains either the pinplace or pinsongplay class. The code I currently have returns a syntax error. What is the corre

Solution 1:

Since Element.classList.contains accepts only a single class name, you need to check each separately.

You could use Array.prototype.some() to avoid writing a bunch of or conditions

const el = document.getElementById('recordplayerstick')
const classNames = ['pinplace', 'pinsongplay']
if (classNames.some(className => el.classList.contains(className))) {
  removeping()
}

Solution 2:

You are going to have to do two checks if you are going to use classList.

functionremovepin() {
  console.log("yep");
}
var cList = document.getElementById('recordplayerstick').classList;
if (
  cList.contains('pinplace') ||
  cList.contains('pinsongplay')) {
  removepin();
}
<divid="recordplayerstick"class="pinplace pinsongplay"></div>

Solution 3:

Use ... (Spread syntax)

Example

const element = document.getElementById("left-sidebar");
const has_some = ["left-sidebar", "js-pinned-left-sidebar"];
const result = [...element.classList].some(className => has_some.indexOf(className) !== -1);  
// has_some.some(className => [...element.classList].indexOf(className) !== -1);// or example like @Phil// has_some.some(className => element.classList.contains(className))

complete functions

/**
 * @description determine if an array contains one or more items from another array.
 * @param {array} haystack the array to search.
 * @param {array} arr the array providing items to check for in the haystack.
 * @return {boolean} true|false if haystack contains at least one item from arr.
 */var findOne = function (haystack, arr) {
    return arr.some(function (v) {
        return haystack.indexOf(v) !== -1;
    });
};

/**
 * @description determine if element has one or more className.
 * @param {HTMLElement} element element where is going to search classNames.
 * @param {array} arrayClassNames Array of Strings, provide to search ClassName in the element
 * @return {boolean} true|false if element.classList contains at least one item from arrayClassNames.
 */var checkElementHasSomeClassName = function (element, arrayClassNames) {
    // uncoment and use this return if you don't want the findOne function// return [...element.classList].some(className => arrayClassNames.indexOf(className) !== -1);return findOne([...element.classList], arrayClassNames);
};

Links extras:

Spread syntax - browser compatibility

Check if exist one item from array in another array

Solution 4:

You can use regular expressions:

let div = document.querySelector("div");

if ( /bubu|moo|bar/i.test(div.className) ) {
  console.log("ok (simple test)");
}

if ( /default|bar/i.test(div.className) ) {
  console.log("not-ok (partial match of `btn-default`)");
}

if ( /(?:^|\s)default|bar(?:\s|$)/i.test(div.className) ) {
  console.log("ok (not logging)");
  // ^ - the beginning of line | or \s space character.// space char | or $ - line ending
}

/***/let names = ["btn", "bar", "bubu"];
let regex = newRegExp( "(?:^|\\s)" + names.join("|") + "(?:\\s|$)", "i");

if ( regex.test(div.className) ) {
  console.log("ok (new RegExp)");
}
<divclass="btn btn-default bubu"></div>

Solution 5:

As already stated in previous answers .classList.contains() can only pass one parameter. The following example features a function that will iterate through a given list of classNames° and returns true should any or all¹ of the classNames are assigned to the targeted DOM node².

° 3rd parameter ...classes ¹ 2nd parameter all ² 1st parameter DOMNode

Usage

findClasses(DOMNode, all, ...classes)
DOMNode.....: The reference to a single DOM element
              ex. const node = document.querySelector('.target'); 
all.........: Booleanto determine whether all classes listed in the 
              third parameter need to be present (true) or just one of
              them (false)
...classes..: ClassNames as a comma delimited list of strings
              ex. "bullseye", "miss"

Example

const node = document.querySelector('#recordplayerstick');

constfindClasses = (node, all, ...classes) => {
  return all ?
    classes.every(cls => node.classList.contains(cls)) :
    classes.some(cls => node.classList.contains(cls));
};

// console.log(findClasses(node, false, 'pinplace', 'pinsongplay'));// returns true// console.log(findClasses(node, true, 'pinplace', 'pinsongplay'));// returns falseconstremovePin = () => alert(`PIN REMOVED!`);

if (findClasses(node, false, 'pinplace', 'pinsongplay')) removePin();
<divid='recordplayerstick'class='pinplace'></div>

Post a Comment for "If Classlist Contains More Than One Specific Class"