I have a webpage that includes some a
tags I want to remove.
Assuming that these a
tags have no identifier and that I also suffice them with identifiers from back end (not my site):
How could I target all these a
elements through their textContent
property?
I already tried these codes:
What have I missed as a JS freshman?
Code 1:
let textToRemove = [
"עריכה",
"עריכת קוד מקור",
"שיחה",
"גרסאות קודמות",
"מזנון",
"כיכר העיר"
];
document.querySelectorAll("a").forEach( e => {
if ( e.textContent == textToRemove ) {
e.style.display = "none"
}
});
Code 2:
let strings = [
"עריכה",
"עריכת קוד מקור",
"שיחה",
"גרסאות קודמות",
"מזנון",
"כיכר העיר"
];
let links = document.querySelectorAll("a");
for ( string as strings) {
if ( links.textContent == strings) {
link.style.display = "none";
}
}
答案 0 :(得分:1)
所以看起来您正在尝试将标记内的文本与strings
/ textToRemove
数组中的字符串进行比较,然后在这些元素匹配时将其隐藏起来?
您的代码中有一些错误。试试这个而不是code1:
var x = document.querySelectorAll("a");
for (var i = 0; i < x.length; i++) {
if (strings.indexOf(x[i].textContent) != -1) {
x[i].style.display = "none";
}
}
您无法使用==
查看数组中是否包含特定字符串。使用indexOf
代替它是有效的,因为它搜索值并返回它的索引(如果它存在)或-1(如果不存在)。
答案 1 :(得分:1)
第二种语法属于PHP。
无论如何,你的第一个代码有一些错误,首先你试图将数组与字符串进行比较,而不是检查该数组是否包含字符串。
2)比较运算符为==
而非=
3)您在)
之前将}
放在函数的末尾
工作代码:
let textToRemove = [
"עריכה",
"עריכת קוד מקור",
"שיחה",
"גרסאות קודמות",
"מזנון",
"כיכר העיר"
];
document.querySelectorAll("a").forEach( e => {
if (textToRemove.indexOf( e.textContent ) > -1 ) {
e.style.display = "none";
}
});