Lessismooore
Lessismooore

Reputation: 13

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

Upvotes: 1

Views: 693

Answers (1)

Dan D.
Dan D.

Reputation: 8577

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

Upvotes: 0

Related Questions