简体   繁体   中英

Changing DOM elements by reference

Let's say I have a paragraph of text in a HTML file. Using TreeWalker I pushed every non-empty text node to an array:

function getTextNodes(elem) {
    var textNodes = [];
    var nextNode;

    var treeWalker = document.createTreeWalker(elem, NodeFilter.SHOW_TEXT, {
        acceptNode: function(node) {
            return node.textContent !== "\n" ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
        }
    }, false);

    var counter = 1;

    while (nextNode = treeWalker.nextNode()) {
        textNodes.push(nextNode);

        console.log("Pushed " + counter + " times.");

        counter++;
    }

    return textNodes;
}

When I try to change the contents of the array, like replacing every element with the string "changed ", nothing happens in the browser window.

Is it somehow possible storing the nodes by reference, such that every time they are changed, the text in the browser changes, too?

EDIT:

function changeTextNodes(elem) {
    for (var i = 0; i < elem.length; i++) {
        elem[i] = "change ";
    }
}

The code that changes the array elements.

EDIT2:

$(document).ready(function() {
    changeTextNodes(getTextNodes(document.body));
});

Here's how the 2 functions are called.

Your code that attempts to change the text examines the array result from gathering up the nodes. That array consists of nodes , so if you want to modify the content you need to do that through the node API. Currently, your code just modifies the array contents, which will have no effect on the DOM; it's just a JavaScript array.

To change the content, you'd modify the nodeValue property:

for (var i = 0; i < elem.length; i++) {
    elem[i].nodeValue = "change ";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM