gpt4 book ai didi

javascript - Userscript,如何替换HTML标签和属性

转载 作者:行者123 更新时间:2023-11-28 02:34:57 26 4
gpt4 key购买 nike

我正在尝试更改 HTML 标签并删除标签后的类/样式属性。如果我事先创建代码并替换,我已经知道如何执行此操作,现在我想知道如何在已加载的页面上找到标签并用我的 js 替换它们。

var s = "<h2 class=\"title\" style=\"font-color: red;\">Blog Post</h2>";
s = s.replace("<h2 class=\"title\" style=\"font-color: red;\">","<p>");
s = s.replace(/<\/h2>/g, "</p>");

开头 <h2 class="title" style="font-color: red;">Blog Post</h2>

结束 <p>Blog Post</p>

所以问题是我如何创建 var s与现有的 HTML?我如何找到h2.title在页面上并将其提供给 var s

编辑 除了我发现并调整的这个脚本之外,我没有任何 JavaScript 经验。请解释我如何从现有文档中获取文本,并将其设为 s.replace 的 var 来操作。

最佳答案

不要尝试使用正则表达式来执行此操作,您应该使用 DOM 操作将有问题的文本节点移动到您创建的 p 标记。这里有一些代码可以满足您的需要。

http://jsfiddle.net/jWRh5/

// Find the h2
var h2 = document.querySelector("h2");
// Create the p element you need
var p = document.createElement("p");
// Move the text node into the p element
p.appendChild(h2.firstChild);
// Insert the p element before the h2
h2.parentNode.insertBefore(p, h2);
// Get rid of the h2
h2.parentNode.removeChild(h2);

如果你想违背其他人的建议,这里有一种使用 RegExp 来实现你需要的方法 http://jsfiddle.net/jWRh5/1/

它使用了一个不太受支持的功能,outerHTML(它可以在主要浏览器的最新版本中工作)

var h2 = document.querySelector("h2.title");
var s = h2.outerHTML;
s = s.replace("<h2 class=\"title\" style=\"font-color: red;\">","<p>");
s = s.replace(/<\/h2>/g, "</p>");
h2.outerHTML = s;

以下是如何对页面上的所有 h2.title 执行此操作(不使用 RegExp 方式,因为这是一种非常糟糕的方式,但如果您确实打算使用它,则可以将其用作指南)

var h2s = document.querySelectorAll("h2.title");
// Loop backwards since we're modifying the list
for (var i = h2s.length -1 ; i >=0; i--) {
var h2 = h2s[i];
var p = document.createElement("p");
p.appendChild(h2.firstChild);
h2.parentNode.insertBefore(p, h2);
h2.parentNode.removeChild(h2);
}

关于javascript - Userscript,如何替换HTML标签和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13595791/

26 4 0