如果班级列表包含多个特定班级

use*_*515 -1 javascript class contains

我需要一个函数来触发该元素是否recordplayerstick包含pinplacepinsongplay类。我当前拥有的代码返回语法错误。正确的方法是什么?

if (document.getElementById('recordplayerstick').classList.contains('pinplace pinsongplay')) {
    removepin();
}
Run Code Online (Sandbox Code Playgroud)

epa*_*llo 12

如果要使用 classList,则必须进行两项检查。

function removepin() {
  console.log("yep");
}
var cList = document.getElementById('recordplayerstick').classList;
if (
  cList.contains('pinplace') ||
  cList.contains('pinsongplay')) {
  removepin();
}
Run Code Online (Sandbox Code Playgroud)
<div id="recordplayerstick" class="pinplace pinsongplay"></div>
Run Code Online (Sandbox Code Playgroud)


Phi*_*hil 7

由于Element.classList.contains仅接受一个类名,因此您需要单独检查每个类名。

您可以Array.prototype.some()用来避免写一堆条件

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


Dar*_*zer 5

使用...扩展语法

例子

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))
Run Code Online (Sandbox Code Playgroud)

功能齐全

/**
 * @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);
};
Run Code Online (Sandbox Code Playgroud)

附加链接:

扩展语法 - 浏览器兼容性

检查另一个数组中是否存在数组中的一项

  • 这似乎不起作用,它只搜索数组中的第一个元素。使类列表成为一个数组,例如 `[...element.classlist].includes('a','b', etc)`? (3认同)