问题描述
<div id="foo" platform="bar" table-index="1">
hello!
</div>
var ele = document.querySelector("#foo").getAttribute("platform")
我可以通过ele变量获取“ bar”。
但是我想在正则表达式中使用getAttribute。
var ele = document.querySelector("#foo").getAttribute(`regex contains just "index"`)
单词“ table-index”以索引结尾。所以我想查找属性并获得1(表索引值),只需使用“索引”和正则表达式即可。
我不知道在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>
,
您将不得不遍历属性以找到名称与RegExp相匹配的属性。
function regexMatch(element,regex) {
let match = [...element.attributes].find(i => regex.test(i.name));
if (!match) return undefined;
return match.value;
}
let ele = regexMatch(document.querySelector("#foo"),/index/g);
console.log(ele);
<div id="foo" platform="bar" table-index="1">
hello!
</div>
,
const match = findAttributeMatch("foo","index");
console.log(document.querySelector('#foo').getAttribute(match));
function findAttributeMatch(id,attribute) {
const regex = RegExp(`(${attribute})`,'gm');
const element = document.querySelector(`#${id}`);
const a = [...element.attributes].find(node => regex.test(node.name));
return a && a["name"];
}
<!DOCTYPE html>
<div id="foo" platform="bar" table-index="1">
hello!
</div>