With this edit I try to be more specific with my question and add my last try to solve the problem: A browser add-on replaces some words on a website. This part works! Now there is some text which should not be replaced. This text is within the class "msg_content", e.g.
<span class="msg_content">don't replace my words</span>.
This part does the replacement-job and should skip elements with class "msg_content":
function replaceText (node) {
if (node.nodeType === Node.TEXT_NODE) {
//skip msg_content
try {
let note = document.querySelector('.msg_content');
if (node == note){
console.log("skip chat-area");
return;
}
} catch (e) {
console.log(e);
}
let content = node.textContent;
for (let [word, emoji] of langMap) {
const regex = regexs.get(word);
content = content.replace(regex, emoji);
}
node.textContent = content;
}
else {
for (let i = 0; i < node.childNodes.length; i++) {
replaceText(node.childNodes[i]);
}
}
}
replaceText(document.body);
The replacement works finde, but it doesn't skip the msg_content.
If you want to check if a string is empty you can use string.length I added string.trim() in case the div contains any whitespace which is common in HTML:
function replaceText (node) {
if (node.nodeType === Node.TEXT_NODE) {
// My try to skip specific area here (doesn't work)
//if (document.getElementById("chatBar")) {
// return;
//}
let content = node.textContent;
if (!content.trim().length) return; // skip if content is empty
for (let [word, emoji] of langMap) {
const regex = regexs.get(word);
content = content.replace(regex, emoji);
}
node.textContent = content;
}
else {
// This node contains more than just text, call replaceText() on each
// of its children.
for (let i = 0; i < node.childNodes.length; i++) {
replaceText(node.childNodes[i]);
}
}
}
replaceText(document.body);