Reputation: 41
Ok, fairly new to js, trying random stuff (custom chrome extension) and here I encountered a problem with mutations from MutationObserver.
So here's the deal. Getting the mutations themselves is no problem, but what I'm trying to do is to get elements from the mutations and edit them so I can see changes on the page. By changes I just mean to edit the text in those elements.
Here is basically what I want to achieve:
var observer = new MutationObserver(function (mutations) {
for (mutation in mutations) {
if(mutation.addedNodes != null && mutation.addedNodes.length > 0)
mutation.addednodes.innerText = "my text";
}
});
observer.observe(document, {childList: true, subtree: true});
Which obviously doesn't work because I think that those mutations are not linked to DOM... or something. I fairly anticipate that this is done on purpose to prevent recursion calling.
Otherwise if there is a way how to edit text of newly added elements to page during users interaction, that would also answer this question.
I'm sorry if this is answered somewhere, but I swear to god I could't find an answer to this.
Upvotes: 1
Views: 2407
Reputation: 41
So based on wOxxOm's suggestions in the comments, I managed to get something like this to work:
function onMutation(mutations) {
for (var i = 0, len = mutations.length; i < len; i++) {
var added = mutations[i].addedNodes;
for (var j = 0, lenAdded = added.length; j < lenAdded; j++) {
var node = added[j];
if (!node.parentNode || !node.textContent.match(pattern)) continue;
editNode(node);
}
}
}
function editNode(node) {
var treeWalker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT);
var textNode;
while (textNode = treeWalker.nextNode()) {
textNode.nodeValue = textNode.nodeValue.replace(pattern, '');
}
}
Upvotes: 2