假设我有以下标记...
<div data-namespace-title="foo"></div>
<div data-namespace-description="bar"></div>
<div data-namespace-button="foo"></div>
无论如何,我可以用 选择它们querySelectorAll
吗?
我试过了document.querySelectorAll([data-namespace-*])
,但这当然行不通
没有简单的方法可以做到这一点,仅仅是因为浏览器没有在属性名称/键(仅在其值上)实现通配符选择器。您可以做的是简单地遍历您的元素集(在这种情况下,它们的公分母是div
),然后将它们过滤掉。
您可以通过调用访问每个 DOM 节点的属性列表<Node>.attributes
,然后将其转换为数组,并检查每个属性中的一个或多个是否name
与正则表达式模式匹配/^data-namespace-.*/gi
:
var els = document.querySelectorAll("div");
var filteredEls = Array.prototype.slice.call(els).filter(function(el) {
var attributes = Array.prototype.slice.call(el.attributes);
// Determine if attributes matches 'data-namespace-*'
// We can break the loop once we encounter the first attribute that matches
for (var i = 0; i < attributes.length; i++) {
var attribute = attributes[i];
// Return the element if it contains a match, and break the loop
if (attribute.name.match(/^data-namespace-.*/gi))
return el;
}
});
console.log(filteredEls);
<div data-namespace-title="foo">title</div>
<div data-namespace-description="bar">description</div>
<div data-namespace-button="foobar">button</div>
<div data-dummy>dummy</div>
更新:如果您熟悉 ES6,它会变得更清晰,因为:
Array.from
代替繁琐的Array.prototype.slice.call(...)
. 专业提示:您还可以使用扩展运算符,即const els = [...document.querySelectorAll("div")]
.Array.some
代替手动创建for
带有返回逻辑的循环const els = Array.from(document.querySelectorAll("div"));
const filteredEls = els.filter(el => {
const attributes = Array.from(el.attributes);
return attributes.some(attribute => attribute.name.match(/^data-namespace-.*/gi));
});
console.log(filteredEls);
<div data-namespace-title="foo">title</div>
<div data-namespace-description="bar">description</div>
<div data-namespace-button="foobar">button</div>
<div data-dummy>dummy</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句