Search code examples
javascripthtmlcssdommaterialize

What Is getInstance Method in MaterializeCSS


I only spent a few hours using the MaterializeCSS framework, and I found code that I don't think I understand and there might not be an explanation in the documentation, can you explain it to me what is the function of the getInstance () method ?

let elems = document.querySelectorAll(".sidenav");
M.Sidenav.getInstance(elems).close();
M.Sidenav.init(elems);

Solution

  • getInstance returns the component and all the data available for it - on which we can use provided methods that vary from component to comonent.

    #1 var elems = document.querySelectorAll('.sidenav');

    This selects all elements with a class of sidenav. If we log elems, we see that it is a nodelist. You will likely only ever have a single sidenav, but you can imagine if were were looking at select inputs, we might have more than one on the page.

    #2 var instances = M.Sidenav.init(elems);

    This initializes the component. In my codepen I log instances[0] - remember that we are selecting potentially multiple elements, and so we need to access them via nodelist index. [0] returns the first instance, or the first sidenav in this case.

    Say you had more than one sidenav, and you wanted to run a method on one of the sidenavs, say to open it. To do that we need to get the specific instance. So we could use the nodelist index - instances[0].open() - or, we could be more explicit:

    #3 var elem = document.querySelector('#mobile-demo');

    This gets a single sidenav via ID (note the use of querySelector instead of querySelectorAll).

    #4 var instance = M.Sidenav.getInstance(elem);

    This gets the specific instance and if we look at the log for instance, we can see that it is identical to using instances[0].

    We can now run instance.open(), or get all kinds of data by inspecting the returned object. Logging instance.options displays the options used to init - in this case none - so we see the default values returned.

    Check the codepen and look at the logs.