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

113
Views
Cree un método JavaScript personalizado para elementos DOM

Los elementos en este entorno están anidados dentro de contenedores, llamémoslos widgets. Dado cualquier elemento, quiero encontrar el widget que lo contiene usando un método personalizado llamado parentWidget . El widget siempre se puede identificar por el nombre de clase "widget". Quiero que esto se comporte exactamente como parentElement , excepto que puede tener varios niveles de profundidad, por lo que debe usar el método de JavaScript .closest() para recorrer el árbol DOM.

Escribí esto, pero no me gusta que necesito usar paréntesis para ejecutar la función:

 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>

En algún momento, es posible que desee concatenar otros métodos, por lo que no querré usar paréntesis (por ejemplo, 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!