我需要一些帮助来从 DOM 树中选择元素。 我需要选择所有包含一个属性的元素,该属性包含 interpolation brackets ==> {{someString}}。
V.I.Note:插值可能是属性值的子串。
例如:
<input id="{{labelID}}">
<div style='background-color:{{backgroundColor}}'>
在这个例子中,我需要在一些数据结构中设置 input 和 div 元素,但是如何选择这些元素。
我尝试遍历所有 DOM 树并检查每个元素是否与某些正则表达式匹配,但此解决方案不起作用,因为如果某些元素具有插值括号,则将选择它的所有祖先 有帮助吗?
最佳答案
如果您事先不知道要搜索的属性的名称,则需要递归遍历 DOM:
// Walk starting at document body
walk(document.body);
function walk(element) {
var n;
// Check its attributes
for (n = 0; n < element.attributes.length; ++n) {
if (element.attributes[n].value.indexOf("{{") != -1) {
// **** This attribute contains {{ ****
}
}
// Walk its children
for (n = 0; n < element.children.length; ++n) {
walk(element.children[n]);
}
}
或者使用forEach
:
// Handy access to forEach
var forEach = Array.prototype.forEach;
// Walk starting at document body
walk(document.body);
function walk(element) {
// Check its attributes
forEach.call(element.attributes, function(attr) {
if (element.attributes[n].value.indexOf("{{") != -1) {
// **** This attribute contains {{ ****
}
});
// Walk its children
forEach.call(element.children, walk);
}
请注意,与 childNodes
不同,children
中的唯一条目是 Element
。
您可能会加强属性检查以同时查找 }}
等,但这是一般的想法。
在 ES2015+ 中:
// Walk starting at document body
walk(document.body);
function walk(element) {
// Check its attributes
[...element.attributes].forEach(attr => {
if (attr.value.includes("{{")) {
// **** This attribute contains {{ ****
}
});
// Walk its children
[...element.children].forEach(walk);
}
关于javascript - 如何根据属性值选择元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43980422/