how to pass attribute in argument to a function

i want to create function to apply any attribute or function to all selectors what is the correct way to do it

function applyToAll(elm,func)
  {
   let i = elm.length; while (i--) { elm[i].func; }
  }

  li = document.querySelectorAll("li");
  hide = style.display = "none";

  applyToAll(li,hide) // Uncaught ReferenceError: style is not defined

i can pass the property direct like this

let i = elm.length; while (i--) { elm[i].style.display = "none"; }

but i want let function dynamic so i can use for example :

prop = innerHTML = "<b>something</b>";
let i = elm.length; while (i--) { elm[i].prop }

Answer

Two changes:

function applyToAll(elm, func) {
    let i = elm.length;
    while (i--) {
        func(elm[i])  // <---
    }
}

li = document.querySelectorAll("li");
hide = e => e.style.display = "none";  // <---


applyToAll(li, hide)

Change 1: func is not a method, and cannot be called with a dot

Change 2: just style.display = ... is an expression which is evaluated immediately, on the other side, e => e.style.display is a function which is evaluated on call.

As a side note, querySelectorAll returns a NodeList which already provides forEach which is exactly what your function does, up to the order of the application.

Leave a Reply

Your email address will not be published. Required fields are marked *