您好,我正在尝试为网页上的所有元素添加一个类。总体目标是抓取网页上的所有元素并添加到类中。 包含字体大小的类将被更改以隐藏消息。
我收到此错误未捕获的类型错误:无法设置空的属性"innerHTML"
我尝试将脚本移动到索引的正文标签之外.html但它仍然不起作用。
另一个问题是我无法将类添加到我选择的所有 ID 中。 我可以像
$("#iconLog").addClass("style"); //this works
但是当我尝试添加这样的类时
empTwo = "#" + temp; //where empTwo is a string that equals "#iconLog"
$("empTwo").addClass("style") //this does not work
我将在下面发布我的整个脚本以供参考
$(function() {
var hideMsg = "f";
var n = hideMsg.length;
var i;
var j;
var holder;
var hideHolder;
// on button click - hide msg
$('#btnHide').on('click', function() {
//grab all IDS ON WEBPAGE
var allElements = document.getElementsByTagName("*");
var allIds = [];
for (var i = 0, n = allElements.length; i < n; ++i) {
var el = allElements[i];
if (el.id) {
allIds.push(el.id);
}
}
//ERRORS HAPPENING IN THIS LOOP
for(var i = 0; i < allElements.length; ++i)
{
console.log(allIds[i]);
try{
var temp = document.getElementById(allIds[i]).id;
}
catch(err){
document.getElementById("*").innerHTML = err.message;
}
tempTwo = "#" + temp;
console.log(tempTwo);
//$("#iconLog").addClass("style") //this works
$("tempTwo").addClass("style"); //this does not work
}
for(i = 0; i < n; i++) {
//set var holder to first value of the message to hide
holder = hideMsg.charCodeAt(i);
for(j = 7; -1 < j; j--) {
//set hideHolder to holders value
hideHolder = holder;
//mask hideHolder to grab the first bit to hide
hideHolder = hideHolder & (1<<j);
//grab the first element ID
if(hideHolder === 0) {
// embed the bit
// bitwise &=
} else {
//embed the bit
// bitwise ^=
}
}
}
});
});
要向所有元素添加一个类,你不需要 for 循环。试试这个:
$("*").addClass("style");
设置所有元素的内部 html 也是如此。试试这个:
$("*").html("Html here");
删除empTwo
中的双引号。当您将变量作为选择器传递时,您不需要引号。变量本身包含一个字符串,因此您不需要引号。
empTwo = "#" + temp;
$(empTwo).addClass("style") //this will work
<</div>
div class="one_answers"> 试试这个:
$(empTwo).addClass("style")
注意:您使用了字符串而不是变量:
好吧,试试这个...
因此,您传递了 quotos 中的变量,而不是将值获取到 empTwo,而是直接搜索"empTwo"。
$(empTwo).addClass("style");
要获得所有元素,请尝试以下操作-
var allElements = = document.body.getElementsByTagName("*");
希望这对您:)有所帮助
empTwo = "#" + temp; //where empTwo is a string that equals "#iconLog"
$("empTwo").addClass("style") //this does not work
你在第二行犯了错误。变量 empTwo 已经采用字符串格式。所以你需要做的就是
$(empTwo).addClass("style") //this works because empTwo returns "#iconLog"