如果 class 列表包含多个特定的 class
If classlist contains more than one specific class
如果元素 recordplayerstick
包含 pinplace
或 pinsongplay
class,我需要一个函数来触发。我目前的代码 returns 有语法错误。正确的做法是什么?
if (document.getElementById('recordplayerstick').classList.contains('pinplace pinsongplay')) {
removepin();
}
如果要使用 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>
由于 Element.classList.contains
只接受一个 class 名称,您需要分别检查每个名称。
您可以使用 Array.prototype.some()
来避免编写一堆 或 条件
const el = document.getElementById('recordplayerstick')
const classNames = ['pinplace', 'pinsongplay']
if (classNames.some(className => el.classList.contains(className))) {
removeping()
}
前面的回答已经说明了.classList.contains()
只能传递一个参数。以下示例具有一个函数,该函数将遍历给定的 className
s° 和 returns true
列表,如果 className
s 中的任何或所有¹被分配给目标 DOM节点².
°第三个参数...类
¹ 第二个参数 all
² 第一个参数 DOMNode
用法
findClasses(DOMNode, all, ...classes)
DOMNode.....: The reference to a single DOM element
ex. const node = document.querySelector('.target');
all.........: Boolean to 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"
例子
const node = document.querySelector('#recordplayerstick');
const findClasses = (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 false
const removePin = () => alert(`PIN REMOVED!`);
if (findClasses(node, false, 'pinplace', 'pinsongplay')) removePin();
<div id='recordplayerstick' class='pinplace'></div>
使用...
(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
您可以使用正则表达式:
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>
如果元素 recordplayerstick
包含 pinplace
或 pinsongplay
class,我需要一个函数来触发。我目前的代码 returns 有语法错误。正确的做法是什么?
if (document.getElementById('recordplayerstick').classList.contains('pinplace pinsongplay')) {
removepin();
}
如果要使用 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>
由于 Element.classList.contains
只接受一个 class 名称,您需要分别检查每个名称。
您可以使用 Array.prototype.some()
来避免编写一堆 或 条件
const el = document.getElementById('recordplayerstick')
const classNames = ['pinplace', 'pinsongplay']
if (classNames.some(className => el.classList.contains(className))) {
removeping()
}
前面的回答已经说明了.classList.contains()
只能传递一个参数。以下示例具有一个函数,该函数将遍历给定的 className
s° 和 returns true
列表,如果 className
s 中的任何或所有¹被分配给目标 DOM节点².
°第三个参数...类
¹ 第二个参数 all
² 第一个参数 DOMNode
用法
findClasses(DOMNode, all, ...classes) DOMNode.....: The reference to a single DOM element ex. const node = document.querySelector('.target'); all.........: Boolean to 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"
例子
const node = document.querySelector('#recordplayerstick');
const findClasses = (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 false
const removePin = () => alert(`PIN REMOVED!`);
if (findClasses(node, false, 'pinplace', 'pinsongplay')) removePin();
<div id='recordplayerstick' class='pinplace'></div>
使用...
(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
您可以使用正则表达式:
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>