Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

How to replace html tag with Tampermonkey?

I want to replace all amp-img tags with img tags on all websites using Tampermonkey, please.

I've tried the following but didn't work

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);

question from:https://stackoverflow.com/questions/65948579/how-to-replace-html-tag-with-tampermonkey

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This function might be what you need, but it's just one of the solutions:

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...