获取占位符文本的父节点

时间:2013-11-08 16:19:34

标签: javascript html

我正在尝试在文档中找到占位符文本(占位符看起来像这样:{{Placeholder}}),然后获取它所在的节点,然后向节点添加属性。到目前为止,我能够找到占位符,但我不知道它是哪个元素。当前代码将我在这里写入控制台3次,因为它位于3个节点中:htmlbodyh1。如何获取项目实际的父节点?

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>

2 个答案:

答案 0 :(得分:3)

这有效:(来自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/(忽略第一个日志,它只是构建jsfiddle的方式)

答案 1 :(得分:0)

我相信这只能通过递归来实现

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

以下是一个示例:http://jsfiddle.net/Ng7j8/