定位所有<a> elements with a certain textContent while no identifier is available

时间:2017-07-25 19:22:15

标签: javascript arrays loops dom properties

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:

  • The first brought undefined.
  • The second brought unexpected identifier.

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";
    }
}

2 个答案:

答案 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";
    }
}); 

https://jsfiddle.net/hf3x5zb0/