Javascript 替换页面上的 HTML 标记

Javascript Replace HTML tag on a page

我需要一个简单的脚本来搜索 HTML 特定代码,这样它就不会显示。

我当前的代码只替换了整个文本。但是如果一个人改了1个item,它就找不到了。

有没有办法制作通配符,找到像这样的文本:

<a href="http://www.yourdomain.com">Thesite</a>

...如果它找到了

<*yourdomain*</a> 

然后它将整个 <a href....>..</a> 替换为 Blank?

我当前的代码是:

function checkLoad(){
    if (document.readyState === "complete") {
        document.body.innerHTML = document.body.innerHTML.replace(
             '<p style="text-align:center;">My Website is <a href="http://www.redriv.com/" target="_blank">redriv</a></p>',
             ""
        );
    } else {
        setTimeout('checkLoad();', 500)
    }
}

RegEx 将是这里最简单的解决方案,<a.*yourdomain.*?\/a> 之类的东西应该可以解决问题。它将删除其中包含 yourdomain 的锚标记(作为属性和属性值 - 您没有指定您想要它的准确度,所以一切都会被触发)。在这里查看:

var html = '<a href="http://www.yourdomain.com">Thesite</a><a href="http://www.goodurlhere.com">Good URL</a><a href="http://www.anothergood.com">Good URL</a>';
var replaced = html.replace(/<a.*yourdomain.*?\/a>/, '');
document.getElementById('f').textContent = html;
document.getElementById('r').textContent = replaced;
p {color: #777}
span {color: black}
<p>Sample markup: <span id="f"></span></p>
<p>After RegEx: <span id="r"></span></p>

故意使用一行示例标记,这样您就可以看到它不会触及其他锚点。


所以你的完整代码是:

function checkLoad(){
    if (document.readyState === "complete") {
        document.body.innerHTML = document.body.innerHTML.replace(/<a.*yourdomain.*?\/a>/, '');
    } else {
        setTimeout('checkLoad();', 500)
    }
}

如果您只想基于 href,可以使用 CSS 规则:

a[href=http://www.yourdomain.com] { display: none; }

要查找任何包含 'yourdomain'href,请使用 *=:

a[href*=yourdomain] { display: none; }

如果您还想包含对锚文本的检查,则需要 JS:

function array(a) { return Array.prototype.slice.call(a); }
function check(a) { return /yourdomain/.test(a.textContent); }
function hide (a) { a.style.display = 'none'; }

var selector = 'a[href*=yourdomain]';
var anchors  = array(document.getQuerySelector(selector));

anchors . filter(check) . forEach(hide);

不,不要为此或任何其他 HTML 操作使用正则表达式。