Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
Create a custom JavaScript method for DOM elements

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 parentWidget. The widget can always be identified by the class name "widget". I want this to behave exactly like parentElement, except that it might be several levels deep, so it should use the JavaScript method .closest() to traverse up the DOM tree.

I wrote this, but I don't like that I need to use parenthesis to execute the function:

Element.prototype.parentWidget = function() {
    return this.closest('.widget');
}

// 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?
*/
:root {
    --btn1: hsl(206, 100%, 52%);
    --btn2: hsl(206, 100%, 40%);
}

.widget {
  display: block;
  top:10px;
  left:10px;
  height: 36px;
  width: 150px;
}

.widget > 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%;
}
<div id="w1"><span>Click to test</span></div>
<div class="widget">
  <div class="style-1">
    <button type="button" class="full" onclick="test(this)">Try Me</button>
  </div>
</div>

At some point, I may want to concatenate other methods, so I won't want to use parenthesis (e.g., el.parentWidget.firstChild, etc.)

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!