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

时间:2017-05-15 13:08:28

标签: javascript css

我需要一些帮助来从DOM树中选择元素。 我需要选择包含一个属性的所有元素,该属性包含插值括号==> {{someString}}

V.I.Note :插值可能是属性值的子串。

例如:

<input id="{{labelID}}">
<div style='background-color:{{backgroundColor}}'>

在这个例子中,我需要在某些数据结构中设置input和div元素,但是如何选择这些元素。

我尝试移动所有DOM树并检查每个元素是否与某个regEx匹配,但是这个解决方案不起作用,因为如果某个元素有插值括号,那么它的所有祖先都将是选 有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

如果您不知道要提前搜索的属性的名称,则需要以递归方式遍历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 s。

您可以收紧属性检查以查找}}等,但这是一般的想法。

在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);
}