我正在尝试使用 JavaScript 替换 DIV 标记中的某些文本,但该标记只有类而不是 ID。我尝试过:
document.getElementByClassName('theClassName').innerHTML = 'text i want to insert in place of the existing text';
这不起作用,我也尝试了上面的方法,但使用 getElementById
但这也不起作用。
更新:
我想我需要解释更多(对不起,我是一个 n00b 编码员)。我正在做的是使用 Swift 将网站加载到 WKWebView 中,然后在加载的页面末尾注入(inject)一个 .JS 文件。在该 .JS 文件中,我尝试执行上述操作,但没有成功。我可以找到一个 DIV 并将其隐藏到目前为止,但事实证明替换文本很困难。
这是我上次尝试过的方法,但这也不起作用:
var classes = document.getElementsByClassName("title-random");
for(var i=0;i<classes.length; i++) {
if(classes[i].innerHTML == "The old text") {
classes[i].innerHTML = "the new text";
break;
}
}
我什至尝试过通用的“查找此文本”并替换它的代码,但没有效果
最佳答案
嗨,如果您在多个 div 上都有该类,则必须通过这样的数组访问:
<!DOCTYPE html>
<html>
<body>
<div class="example">First div element with class="example".</div>
<div class="example">Second div element with class="example".</div>
<p>Click the button to change the text of the first div element with class="example" (index 0).</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p>
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
x[0].innerHTML = "Hello World!";
}
</script>
</body>
</html>
关于javascript - 如何使用注入(inject) WKWebView 的 Javascript 替换仅具有类而无 id 的 DIV 标记中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33599544/