user7227263
user7227263

Reputation:

How to select the elements according to the value of the attributes?

I need some help in selecting element from the DOM tree. I need to select all the elements that contains an attribute that holds interpolation brackets ==> {{someString}}.

V.I.Note: the interpolation might be substring of the attribute value.

for example:

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

in this example, I need to set the input and div element in some data structure, but how to select these elements.

I tried to move over all the DOM tree and check each element if it match some regEx, but this solution doesn't work, because if some element has the interpolation brackets then all it's ancestors will be selected any help?

Upvotes: 0

Views: 50

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073998

If you don't know the name(s) of the attribute(s) you want to search in advance, you'll need to recursively walk the 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]);
    }
}

Or using 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);
}

Note that unlike childNodes, the only entries in children are Elements.

You might tighten up the attribute check to also look for }}, etc., but that's the general idea.


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

Upvotes: 1

Related Questions