简体   繁体   中英

Without jQuery, how could I selectively remove elements that exist in an array?

I'm just getting started with Javascript for about a week now, after creating a few Tampermonkey scripts.

The page I'm working on has dynamic elements that basically pop up at random with each page load. For example, sometimes the page will only have a "here" element loaded, and on a different page load, I might see only "what" and "doing" loaded instead. On each page load, I'm hoping to have my script scan for all of these elements, and remove any that have loaded.

Thankfully, their selector paths are easy to find, but I'm looking to find a better looking / easier way to have my script find any of these 5 elements. Here's the layout that's been working:

var what = document.querySelector('#wrapper > footer > div > div > div:nth-child(3) > span')
var am = document.querySelector('#wrapper > footer > div > div > div:nth-child(2) > span')
var i = document.querySelector('#wrapper > footer > div > div > div:nth-child(36) > span')
var doing = document.querySelector('#wrapper > footer > div > div > div:nth-child(4) > span')
var here = document.querySelector('#wrapper > footer > div > div > div:nth-child(5) > span')

if (what) {
    what.remove();
}
if (am) {
    am.remove();
}
if (i) {
    i.remove();
}
if (doing) {
    doing.remove();
}
if (here) {
    here.remove();
}

Having a TON of IF statements will work of course, and I've got a strong feeling that adding all my vars into an array would be the cleanest method, but after looking into arrays and array statements so far, I don't quite yet know what would be my best option.

Ideally, I'm trying to aim for something like:

var group = [what, am, i, doing, here]
if (group.includes == true)
true.remove();

..or something like that. Is there a much better way to do this than my current method with using a flood of IF statements?

Almost there - just loop through group with forEach and remove each item if it exists:

var what = document.querySelector('#wrapper > footer > div > div > div:nth-child(3) > span')
var am = document.querySelector('#wrapper > footer > div > div > div:nth-child(2) > span')
var i = document.querySelector('#wrapper > footer > div > div > div:nth-child(36) > span')
var doing = document.querySelector('#wrapper > footer > div > div > div:nth-child(4) > span')
var here = document.querySelector('#wrapper > footer > div > div > div:nth-child(5) > span')

var group = [what, am, i, doing, here];

group.forEach(item => {
    if (item) item.remove();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM