繁体   English   中英

用户脚本,如何替换HTML标签和属性

[英]Userscript, how to replace HTML tag and attributes

我正在尝试更改HTML标记并在标记后删除class / style属性。 如果我先创建代码并替换,我已经知道如何执行此操作,现在我想知道如何在已经加载的页面上找到标签并将其替换为我的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> 结尾

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

编辑除了我发现并调整过的脚本外,我没有任何JavaScript经验。 请说明如何从现有文档中获取文本,并使其成为s.replace的变量。

请勿尝试使用正则表达式来执行此操作,而应使用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.titles进行操作的方法(不使用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);
} 

对于这种事情, jQuery派了大笔红利,就像快钱一样。

做你想要的代码是:

$("h2").replaceWith ( function () {
    return '<p>' + this.textContent + '</p>';
} );


或者,如果您想更具体:

$("h2.title").replaceWith ( function () {
    return '<p>' + this.textContent + '</p>';
} );


请注意, 该代码修复了所有 <h2>元素(第一个块),或者仅修复了所有具有类title<h2>元素(第二个块)。


有关如何在用户脚本中包含jQuery的信息, 请参阅此答案以了解跨浏览器方法。

.replaceWith()函数的文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM