Удалить все содержимое между двумя тегами комментариев, используя JavaScript - PullRequest
0 голосов
/ 18 октября 2018

Как я могу удалить все содержимое между двумя тегами, если они не входят в стандартные теги;

<!--googleoff: index-->
    some codes and content here...
<!--googleon: index-->

Это реклама, которая показывается на одном сайте, и я хотел бы заблокировать и удалить тему вбраузер от пользователя JS

1 Ответ

0 голосов
/ 18 октября 2018

Это узлы комментариев, а не теги.Лучше всего было бы определить родителя, а затем перебрать детей;см. комментарии:

// Assuming a single parent
let parent = document.querySelector(".stuff");
if (parent) {
    // Uncomment if you want to see nodes before the change
    // showNodes("before", parent);
    let removing = false;
    let child = parent.firstChild;
    let next = null;
    // While we still have child elements to process...
    while (child) {
        // If we're already removing, remember that
        let removeThis = removing;
        // Before we remove anything, identify the next child to visit
        next = child.nextSibling;
        // Is this a comment node?
        if (child.nodeType === Node.COMMENT_NODE) {
            if (child.nodeValue.includes("googleoff: index")) {
                // It's the node that tells us to start removing:
                // Turn on our flag and also remove this node
                removing = true;
                removeThis = true;
            } else if (child.nodeValue.includes("googleon: index")) {
                // It's the node that tells us to stop removing:
                // Turn off our flag, but do remove this node
                removing = false;
                removeThis = true;
            }
        }
        if (removeThis) {
            // This is either stuff in-between the two comment nodes
            // or one of the comment nodes; either way, remove it
            parent.removeChild(child);
        }

        // Move on to next child
        child = next;
    }
    // Uncomment if you want to see nodes before the change
    // showNodes("after", parent);
}

Live Пример:

// Brief delay so you can see it happen
setTimeout(() => {
    // Assuming a single parent
    let parent = document.querySelector(".stuff");
    if (parent) {
        // Uncomment if you want to see nodes before the change
        // showNodes("before", parent);
        let removing = false;
        let child = parent.firstChild;
        let next = null;
        // While we still have child elements to process...
        while (child) {
            // If we're already removing, remember that
            let removeThis = removing;
            // Before we remove anything, identify the next child to visit
            next = child.nextSibling;
            // Is this a comment node?
            if (child.nodeType === Node.COMMENT_NODE) {
                if (child.nodeValue.includes("googleoff: index")) {
                    // It's the node that tells us to start removing:
                    // Turn on our flag and also remove this node
                    removing = true;
                    removeThis = true;
                } else if (child.nodeValue.includes("googleon: index")) {
                    // It's the node that tells us to stop removing:
                    // Turn off our flag, but do remove this node
                    removing = false;
                    removeThis = true;
                }
            }
            if (removeThis) {
                // This is either stuff in-between the two comment nodes
                // or one of the comment nodes; either way, remove it
                parent.removeChild(child);
            }

            // Move on to next child
            child = next;
        }
        // Uncomment if you want to see nodes before the change
        // showNodes("after", parent);
    }
}, 800);


function showNodes(label, parent) {
    console.log(label);
    for (let child = parent.firstChild; child; child = child.nextSibling) {
        console.log(child.nodeType, child.nodeValue);
    }
}
<div>
  Just some content that isn't related
</div>
<div class="stuff">
  This is the parent element
  <!--googleoff: index-->
  some codes and content here...
  <!--googleon: index-->
</div>

Если этот материал появляется в более чем одном месте, очевидно, оберните его в цикле.

Если вы не можете определить родителя,вам придется пройтись по DOM до конца, это немного больше работы (рекурсивная функция), но не так уж плохо.

...