javascript - 如何根据属性值选择元素?

标签 javascript css

我需要一些帮助来从 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/

相关文章:

jquery - 更改动画元素的CSS

html - 如何在不使用 ID 首选项的情况下更改链接的颜色?

html - Css animate/show div after other

css - 将 Prezi 框架变成纯色 - css 代码

javascript - 有没有办法在Python中从浏览器获取当前的HTML?

php - 尝试使用 JavaScript 每 3 分钟调用一次函数

javascript - Angular Directive(指令) : return object from collection

javascript - 如何使用 javascript 检查密码中的特殊字符

javascript - 使用 CSS3 和 jQuery 按顺序对元素进行动画处理

javascript - 垂直展开元素以填充