以下のページ様の改良なのですが
Google翻訳でページを翻訳すると語順がめちゃくちゃになるのを回避するブックマークレット | 迫真の氷結晶
こちらのページ様のブックマークレットだと、以下のようなHTMLもspanに変換されてしまい、コードもすべて翻訳されてしまいます。
<pre>
<code>
const a = 1;
console.log(a);
</code>
<pre>
👆preタグの中をさらにcodeタグで囲うパターンは結構よく見る
なので、以下のように
- 上位にpreタグがある場合はスキップする
- 見やすいようにスタイル調整(色、背景色、padding、角丸、フォント)
調整しました。
document.querySelectorAll("code").forEach(function (e) {
if (e.closest("pre")) {
return;
}
const newElem = document.createElement("span");
while (e.firstChild) {
newElem.appendChild(e.firstChild);
}
for (let index = e.attributes.length - 1; index >= 0; --index) {
newElem.attributes.setNamedItem(e.attributes[index].cloneNode());
}
newElem.style.backgroundColor = "#e5e5e5";
newElem.style.color = "#404040";
newElem.style.paddingLeft = "5px";
newElem.style.paddingRight = "5px";
newElem.style.borderRadius = "2px";
newElem.style.fontFamily = "monospace";
e.parentNode.replaceChild(newElem, e);
});
おわり
コメント