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

241
Views
¿Es posible obtener el objeto jQuery desde $('#myElement')?

Estoy trabajando en un entorno mixto de prototipo/scriptaculous y jQuery. No es mi implementación, pero ahora es mi problema: estoy trabajando para eliminar prototipo/scriptaculous en todas partes y reemplazar ambos con vanillaJS según lo permita el tiempo.

Mientras tanto, digamos que tengo un elemento DOM, a jQuery le gustaría esto:

$("#miElemento")

¿Es posible obtener el objeto jQuery de esto para no tener que pasar '$' de una función a otra como un parámetro adicional? p.ej:

 function foo($) { const myElement = $("#myElement"); ...do some stuff to myElement here... bar(myElement); } function bar(myElementIn) { const $ = {somehow get the jQuery object from myElementIn}; ...do more stuff with other elements related to myElementIn... }

Longshot, estoy seguro, pero pensé que valía la pena preguntar.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Puede usar Object.getPrototypeOf para obtener el prototipo de jQuery y .constructor para luego obtener jQuery.

 const myElementIn = $(/* ... */); console.log(Object.getPrototypeOf(myElementIn).constructor === $);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

about 4 years ago · Juan Pablo Isaza Report

0

Para obtener el elemento DOM, puede usar el método jQuery .get() https://api.jquery.com/get/

Por ejemplo, usando su selector de ID: const myElement = $("#myElement").get()

Si solo quiere el primero en un conjunto const myElement = $(".my-class").get(0);

También puede hacer lo que ha señalado creando un objeto en caché. Ejemplos:

 const myElement = $("#myElement"); myElement.html("<div>new html</div>"); myElement.append("<button>New Button text</button>"); myelement.find('span').trigger('click'); doMoreFunction(myElement); function doMoreFunction(jqEl){ jqEl.find('button').text("Updated Button Text"); }

Aquí hay otro ejemplo: Configuración: tiene un documento que incluye un <iframe> (ambos en el mismo dominio) y desea llamar a jQuery en la ventana principal (suponga que aquí para nuestra demostración es la ventana SUPERIOR en caso de que haya anidado iframes)

Bien, ahora que tenemos algunos "conceptos básicos" fuera del camino, aquí hay un ejemplo para obtener una referencia a jQuery (un poco raro) dentro de una función que se pasa a un objeto jQuery.

 var mybody = jQuery('body') .append('<div id="my-new-thing">I append to the top window DOM</div>'); //This assumes the top window has jQuery referenced in it via a script element for example const newThing = jQuery('#my-new-thing'); newThing.append('<span>New Span For our element</span>'); // console.log(newThing);// commented out as too long for here :) console.log(newThing.constructor); console.log(newThing.constructor == jQuery); // logs true function testMe(me) { console.log(me.constructor == jQuery); let jq = me.constructor; jq(me.get(0)).append("<span> More New</span>"); } testMe(newThing);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

about 4 years ago · Juan Pablo Isaza Report
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!