<div id="foo" platform="bar" table-index="1">
hello!
</div>
如果我使用 getAttribute 方法并获取值,它将是这样的
var ele = document.querySelector("#foo").getAttribute("platform")
我可以通过 ele 变量获得“bar”。
但我想将 getAttribute 与正则表达式一起使用。
var ele = document.querySelector("#foo").getAttribute(`regex contains just "index"`)
单词“table-index”以索引结尾。所以我想找到属性并获得 1(table-index value) 只需使用“索引”和正则表达式。
我不知道在 attiributeName 中使用正则表达式的方法。
getAttribute
不能以这种方式使用——它接受一个字符串作为参数,而不是一个正则表达式。但是,您可以实现一种做类似事情的方法。下面的方法通过使用attributes
元素的 [ ] 属性,然后迭代它们,搜索与正则表达式匹配的元素,然后返回该值。
请注意,此特定实现天真地假设您使用的正则表达式仅匹配元素上的单个属性并返回它遇到的第一个匹配项——但是,您可以更聪明地编写一些更健壮的东西来返回一个数组匹配的属性/值对。
function getAttributeByRegex(element, regex) {
const attributes = element.attributes;
for (let i = attributes.length - 1; i >= 0; i--) {
const attr = attributes[i];
if (regex.test(attr.name)) {
return attr.value;
}
return undefined;
}
}
const value = getAttributeByRegex(
document.querySelector('#foo'),
/-index/
);
console.log(value);
<div id="foo" platform="bar" table-index="1">
hello!
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句