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

时间:2019-01-14 23:37:05

标签: javascript class contains

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

if (document.getElementById('recordplayerstick').classList.contains('pinplace pinsongplay')) {
    removepin();
}

5 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:1)

如果要使用classList,则必须做两次检查。

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

答案 2 :(得分:1)

使用...Spread syntax

示例

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))

完成功能

/**
 * @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);
};

链接附加内容:

Spread syntax - browser compatibility

Check if exist one item from array in another array

答案 3 :(得分:0)

DOMTokenList

通过使用classList界面可以直接访问DOMTokenList。它具有几种方法和属性。下面的演示使用.value属性提取列表,然后使用find()filter()处理多个参数,并使用includes()返回第一个找到的参数或数组找到所有参数。
用法

findClass(selector, array, all)
/*
CSS selector string of tag. ex. "#target"
Array of classes            ex. ["bullseye", "miss"]
Optional: default false: 
                  Returns the first class found.         ex. "bullseye"
                  true: 
                  Returns all classes found as an array. ex. ["bullseye", "miss"]*/


演示

const findClass = (selector, array, all) => {

  let DTL = document.querySelector(selector).classList.value;
  console.log(`DOMTokenList: ${DTL}`);

  if (all) {
    return array.filter((tok) => DTL.includes(tok));
  } else {
    return array.find((tok) => DTL.includes(tok));
  }
};

console.log(findClass('div', ['two', 'four']));

console.log(findClass('div', ['two', 'four'], true));
<div class='one two three four five'></div>

答案 4 :(得分:0)

您可以使用正则表达式:

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 = new RegExp( "(?:^|\\s)" + names.join("|") + "(?:\\s|$)", "i");

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