【问题标题】:How to replace html tag with Tampermonkey?如何用 Tampermonkey 替换 html 标签?
【发布时间】:2021-01-29 12:30:01
【问题描述】:

我想在所有使用 Tampermonkey 的网站上用 img 标签替换所有 amp-img 标签。

我尝试了以下方法,但没有成功

var wns = document.getElementsByTagName("amp-img");
var lmn = document.createElement("img");
var index;

// Copy the children
while (amp-img.firstChild) {
    img.appendChild(amp-img.firstChild); // *Moves* the child
}

// Copy the attributes
for (index = amp-img.attributes.length - 1; index >= 0; --index) {
    img.attributes.setNamedItem(amp-img.attributes[index].cloneNode());
}

// Replace it
amp-img.parentNode.replaceChild(img, amp-img);

【问题讨论】:

  • amp-img怎么能成为js中的标识符呢? “破折号”导致语法错误

标签: html replace tampermonkey


【解决方案1】:

此功能可能是您所需要的,但它只是其中一种解决方案:

function replace_tag(from_tag,to_tag){
    var eles = document.querySelectorAll(from_tag);

    for (let i=0; i<eles.length; i++){
        try{ // Avoid no-parent elements
            let new_html = eles[i].outerHTML.replaceAll("<"+from_tag, "<"+to_tag);
                new_html = new_html.replaceAll("/"+from_tag+">", "/"+to_tag+">");
            eles[i].outerHTML = new_html;
        }
        catch (e){}        
    }
}

// Todo: Fix a bit for mixed-case tag
replace_tag("amp-img","img");

【讨论】:

    猜你喜欢
    • 2020-12-24
    • 2015-07-22
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    相关资源
    最近更新 更多