gpt4 book ai didi

javascript - CSS或JS修改(替换)网页上的每一个字

转载 作者:搜寻专家 更新时间:2023-10-31 22:24:41 24 4
gpt4 key购买 nike

对于彩蛋,我希望能够用常量字符串替换我网页上的每个单词。现有问题侧重于替换某些 单词、不包含许多其他元素的元素,或使用 JQuery 等库。应保留结构,即 <li>Some text <span>link</span> more text</li>应该变成 <li>Lorem Lorem <span>Lorem</span> Lorem Lorem</li> .

如果我像这样遍历 DOM:

recur (el) {
if (typeof el === 'undefined') {
el = document.body
}
for (let e of el.childNodes) {
if (e.nodeType === 1) {
recur(e)
} else if (e.nodeType === 3) {
console.log(e)
}
}
}

我得到了很多 #text元素和看起来像字符串的东西。我怎样才能真正改变它们?我尝试分配给父数组中的相应元素,但这不起作用:

Uncaught TypeError: Failed to set an indexed property on 'NodeList': Index property setter is not supported.

修改这样的文本节点的父节点的innerHTML属性是否更好?

或者您会推荐完全不同的方法吗?纯 CSS 解决方案也很棒。

最佳答案

真有趣!您可以获取并分配给文本节点的 nodeValue。正则表达式至少会让你真正接近 /[\w\x7f-\xff]+/g (十六进制值匹配大部分特殊字符。 See here )

(function recur (el) {
if (typeof el === 'undefined') {
el = document.body
}
for (let e of el.childNodes) {
if (e.nodeType === Node.ELEMENT_NODE) {
recur(e)
} else if (e.nodeType === Node.TEXT_NODE) {
e.nodeValue = e.nodeValue.replace(/[\w\x7f-\xff]+/g, 'lorem')
}
}
})();
<html>
<head>
<title>
A Simple HTML Document
</title>
</head>
<body>
<p>This is a very schön HTML document</p>
<p>It only has <b>two</b> paragraphs</p>
</body>
</html>

关于javascript - CSS或JS修改(替换)网页上的每一个字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48310924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com