1

I am trying to find placeholder text (A placeholder looks like this: {{Placeholder}}) within a document, then get the node that it is apart of, then add an attribute to the node. So far I am able to find the placeholder but I don't know which element it is apart of. The current code writes I am here to the console 3 times because it is in 3 nodes: html, body and h1. How can it get the items actual parent node?

JavaScript:

function getPlaceholders(){
    var elements = document.getElementsByTagName("*");
    for(var e in elements){
        var element = elements[e];
        var html = element.innerHTML;
        if(html && (matches = html.match(/{{(.+)}}/g))){
            console.log("I am here");
        }
    }
}

HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <h1>Hello {{name}}!</h1>
    </body>
</html>
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

2 Answers2

3

This works: (code from here)

function getPlaceholders(){
    var elements = document.getElementsByTagName("*");
    for(var e in elements){
        var element = elements[e];
        child = element.firstChild,
        texts = [];

        while (child) {
            if (child.nodeType == 3) {
                texts.push(child.data);
            }
            child = child.nextSibling;
        }

        var html = texts.join("");
        if(html && (matches = html.match(/{{(.+)}}/g))){
            console.log(html);
        }
    }
}

http://jsfiddle.net/wumm/2VjVa/ (Ignore the first log, it's just of the way jsfiddle is built)

Community
  • 1
  • 1
idmean
  • 14,540
  • 9
  • 54
  • 83
0

I believe this can be achieved only by recursion

function getPlaceholders(elem) {
    // we search for the {{...}} pattern ONLY for this element
    var html = elem.firstChild.data;
    if(html && (matches = html.match(/{{(.+)}}/g))){
        console.log(elem, "I am here");
    }

    // if there are any descendants of this elem, we also call the getPlaceholders function for them
    var elements = elem.children;
    if (elements.length) {
        for(var i = 0; i < elements.length; i++) {
            getPlaceholders(elements[i]);
        }
    }
}

//starting at the body
getPlaceholders(document.body);

Here's an example: http://jsfiddle.net/Ng7j8/

matewka
  • 9,912
  • 2
  • 32
  • 43