title: Create a custom JavaScript method for DOM elements
body: <p>Elements in this environment are nested inside containers - let's call them widgets.  Given any element, I want to find its containing widget using a custom method called <code>parentWidget</code>.  The widget can always be identified by the class name &quot;widget&quot;.  I want this to behave exactly like <code>parentElement</code>, except that it might be several levels deep, so it should use the JavaScript method <code>.closest()</code> to traverse up the DOM tree.</p>
  <p>I wrote this, but I don't like that I need to use parenthesis to execute the function:</p>
  <pre><code>Element.prototype.parentWidget = function() {
      return this.closest('.widget');
  }
  </code></pre>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>// Custom method
  Element.prototype.parentWidget = function() {
      return this.closest('.widget');
  }
  
  // Works
  function test(el) {
    var widget = el.parentWidget();
    var result = document.getElementById("w1");
    result.firstChild.innerText = widget;
  }
  
  /* This is a silly example to illustrate what I'm 
   * trying to achieve, except that I don't want to 
   * require parenthesis.  Instead, I want this to 
   * seem like a native method like, 'parentNode' or 
   * 'firstChild'
   *
   * How can I rewrite this?
  */</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
      --btn1: hsl(206, 100%, 52%);
      --btn2: hsl(206, 100%, 40%);
  }
  
  .widget {
    display: block;
    top:10px;
    left:10px;
    height: 36px;
    width: 150px;
  }
  
  .widget &gt; div {
    height: inherit;
    width: inherit;
  }
  
  .style-1 button {
      color: white;
      background-color: var(--btn1);
      border: none;
      border-radius: 3px;
      transition: background .25s;
  }
  
  .style-1 button:not([disabled]):hover {
      background-color: var(--btn2);
  }
  
  .full {
    height: 100%;
    width:100%;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="w1"&gt;&lt;span&gt;Click to test&lt;/span&gt;&lt;/div&gt;
  &lt;div class="widget"&gt;
    &lt;div class="style-1"&gt;
      &lt;button type="button" class="full" onclick="test(this)"&gt;Try Me&lt;/button&gt;
    &lt;/div&gt;
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  <p>At some point, I may want to concatenate other methods, so I won't want to use parenthesis (e.g., <code>el.parentWidget.firstChild</code>, etc.)</p>