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

446
Views
¿Cómo puedo detectar cuando se ha agregado un nuevo elemento al documento en jquery?

¿Cómo puedo detectar cuando se ha agregado un nuevo elemento al documento en jquery?

Explicación: Quiero saber cuándo se ha agregado al documento un elemento con la clase "encabezado de columna". Como planeo ejecutar algo de javascript en esos elementos.

Cómo puedo hacer esto ? Yo uso la biblioteca jQuery javascript.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

La respuesta aceptada usa un complemento obsoleto de 2011 y la respuesta más votada usa eventos de mutación que ahora están obsoletos .

Hoy, un MutationObserver es lo que debe usar para detectar cuándo se ha agregado un elemento al DOM. MutationObservers ahora es ampliamente compatible con todos los navegadores modernos (Chrome 26+, Firefox 14+, IE11, Edge, Opera 15+, etc.).

Aquí hay un ejemplo simple de cómo puede usar un MutationObserver para escuchar cuando se agrega un elemento al DOM.

Para abreviar, estoy usando la sintaxis de jQuery para construir el nodo e insertarlo en el DOM.

 var myElement = $("<div>hello world</div>")[0]; var observer = new MutationObserver(function(mutations) { if (document.contains(myElement)) { console.log("It's in the DOM!"); observer.disconnect(); } }); observer.observe(document, {attributes: false, childList: true, characterData: false, subtree:true}); $("body").append(myElement); // console.log: It's in the DOM!

El controlador de eventos del observer se activará cada vez que se agregue o elimine un nodo del document . Dentro del controlador, luego realizamos una verificación de contains para determinar si myElement ahora está en el document .

No necesita iterar sobre cada MutationRecord almacenado en mutations porque puede realizar la verificación document.contains directamente en myElement .

Para mejorar el rendimiento, reemplace el document con el elemento específico que contendrá myElement en el DOM.

over 4 years ago · Santiago Trujillo Report

0

$(document).bind('DOMNodeInserted', function(e) { console.log(e.target, ' was inserted'); });

DOMNodeInserted es un evento de nivel 3 de DOM. Eso a su vez significa que necesita un navegador bastante nuevo para soportar ese tipo de evento.

Referencia: MDC

over 4 years ago · Santiago Trujillo Report

0

Si desea hacer algo de jQuery, también puede hacer algo como livequery (complemento adicional) :

 $('column-header').livequery(function() { // do things here with your column-header, like binding new events and stuff. // this function is called when an object is added. // check the API for the deletion function and so on. });

ACTUALIZACIÓN : Parece que el enlace estaba roto. Prueba este enlace

over 4 years ago · Santiago Trujillo 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!