我正在尝试向div中的adblock用户添加自定义HTML代码,称为“cfmonitor”。目前我正在使用下面提到的脚本。
<script>
window.onload = function(){
setTimeout(function() {
var ad = document.querySelector("ins.adsbygoogle");
if (ad && ad.innerHTML.replace(/s/g, "").length == 0) {
ad.style.cssText = 'display:block !important';
document.getElementById("cfmonitor").innerHTML = 'html code goes here';
}
}, 500);
};
</script>
问题 - 此代码只用我的自定义html代码替换第一个cfmonitor div。我有多个div“cfmonitor”。如何用我的自定义HTML代码替换所有“cfmonitor”div?试图尝试很多但失败了,任何人都可以帮助我吗?
您应该像其他人建议的那样使用类名。然后,您将需要遍历返回的元素数组。
var elms = document.getElementsByClassName('cfmonitor');
for (var i = 0; i < elms.length; i++) {
elms[i].innerHTML = 'hi';
}
我建议将cfmonitor
从元素ID移动到类。元素ID也必须是唯一的。如果你这样做,你可以改变这个:
<div class="cfmonitor">how</div>
<div class="cfmonitor">are</div>
<div class="cfmonitor">you</div>
对此:
<div class="cfmonitor">GREAT!</div>
<div class="cfmonitor">GREAT!</div>
<div class="cfmonitor">GREAT!</div>
通过使用此代码(自标记以来使用jQuery)
$(".cfmonitor").html("GREAT!");
如果你在div上使用Id(s)名称然后使用getElementById连接javascript最好
<div id="first_div">THIS IS THE WORDING YOU WANT TO CHANGE</div>
<div id="first_div">THIS IS THE WORDING YOU WANT TO CHANGE</div>
<div id="first_div">THIS IS THE WORDING YOU WANT TO CHANGE</div>
<script>
document.getElementById('first_div').innerHTML = "Change Text to the following ";
</script>