[英]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
標簽。 這是一些可以滿足您需求的代碼。
// 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的信息, 請參閱此答案以了解跨瀏覽器方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.