如何用 Tampermonkey 替换 html 标签?
How to replace html tag with Tampermonkey?
我想使用 Tampermonkey 将所有网站上的所有 amp-img 标签替换为 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);
这个功能可能是您所需要的,但它只是解决方案之一:
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");
我想使用 Tampermonkey 将所有网站上的所有 amp-img 标签替换为 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);
这个功能可能是您所需要的,但它只是解决方案之一:
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");