1
function removeIcons(x) {
  x.forEach(function (element) {
  element.remove()
  })
}

removeIcons(document.querySelectorAll(".film-icon"))
removeIcons(document.querySelectorAll(".music-icon"))
removeIcons(document.querySelectorAll(".book-icon"))
removeIcons(document.querySelectorAll(".software-icon"))
removeIcons(document.querySelectorAll(".smile-icon"))
removeIcons(document.querySelectorAll(".article-icon"))

How can I write it simplier? I mean, the name of the function shouldn't repeat.

5
  • Have you tried to solve this? Where did you get stuck? Commented Apr 27, 2020 at 12:03
  • 4
    Just select all elements with a single selector? removeIcons(document.querySelectorAll(".film-icon,.music-icon,.book-icon,...")) Commented Apr 27, 2020 at 12:03
  • 2
    You could also incorporate the querySelectorAll into your function: if(typeof x==='string') x = document.querySelectorAll(x);. That way you can call it with a string or NodeList Commented Apr 27, 2020 at 12:06
  • 1
    If only those icons use class names ending on -icon, you can have a more concise selector for all icons: '[class$="-icon"]' Commented Apr 27, 2020 at 12:06
  • Thanks to everyone, I'm very grateful for your help. fjc, I had no idea how to go about it. I couldn't find anything on Google. Felix Kling and Mamun - that seems to me the best solution. David784 - very interesting, I'll keep that in mind. Connexo - I'll use that too. Commented Apr 28, 2020 at 9:52

2 Answers 2

2

You can target all the elements at once by specify the classes separated by comma using Document.querySelectorAll():

removeIcons(document.querySelectorAll(".film-icon, .music-icon, .book-icon, .software-icon, .smile-icon, .article-icon"));
Sign up to request clarification or add additional context in comments.

1 Comment

It's either Document.prototype.querySelectorAll or document.querySelectorAll. querySelectorAll is not a static method.
2

You can use map to do your task as

var iconlist = [".film-icon", ".music-icon", ".book-icon", ".software-icon", ".smile-icon", ".article-icon"];
iconlist.map(item => removeIcons(document.querySelectorAll(item));

2 Comments

I think forEach is more appropriate. Map works, but it is generally used when you want to apply a function to every item and create a new list with them. Since we are not using the return value from returnIcons, forEach fits.
Hien Nguyen and Dejke. Thanks a lot for yur answers. I haven't got enough knowledge to comment on what you wrote. This arrow (=>) I have already seen on a course and at the beginning I suspected it would be part of the solution to my problem, but the solution proposed by Felix Kling and Mamun appeals most to me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.