Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

MutationObserver

Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.

MutationObserver establece un mecanismo para reaccionar antes cambios en el DOM. Ha sido diseñado como un sustituto de los Mutation Events definidos en las especificaciones de DOM3 Events.

Constructor

MutationObserver()

Constructor para la instaciación de nuevos DOM mutation observers.

MutationObserver(
  function callback
);
Parámetros
callback
La función que será llamada en cada mutación del DOM. El observer llamará a esta función con dos argumentos. El primero es un array de objetos, cada uno del tipo MutationRecord. El segundo es la propia instancia del MutationObserver.

Métodos

void observe( Node target, MutationObserverInit options );
void disconnect();
Array takeRecords();

observe()

Registra la instancia del MutationObserver  para recibir notificaciones de las mutaciones del DOM sobre el nodo especificado.

void observe(
  Node target,
  MutationObserverInit options
);
Parámetros
target
El Node sobre el que observar las mutaciones del DOM.
options
Un objeto MutationObserverInit, que especifica que mutaciones del DOM deben ser informadas.
NOTE: Adding an observer to an element is just like addEventListener, if you observe the element multiple times it does not make a difference. Meaning if you observe element twice, the observe callback does not fire twice, nor will you have to run disconnect() twice. In other words, once an element is observed, observing it again with the same observer instance will do nothing. However if the callback object is different it will of course add another observer to it.

disconnect()

Evita que la instancia de MutationObserver continue recibiendo notificaciones de modificaciones del DOM. Hasta que el método observe() sea usado de nuevo, la función callback no será invocada.

void disconnect();

takeRecords()

Vacía la cola de registros de la instancia de MutationObserver devolviendo su contenido.

Array takeRecords();
Return value

Returns an Array of MutationRecords.

MutationObserverInit

MutationObserverInit es un objeto para el que se pueden especificar las siguientes propiedades:

NOTE: At the very least, childList, attributes, or characterData must be set to true. Otherwise, "An invalid or illegal string was specified" error is thrown.
Property Description
childList Set to true if additions and removals of the target node's child elements (including text nodes) are to be observed.
attributes Set to true if mutations to target's attributes are to be observed.
characterData Set to true if mutations to target's data are to be observed.
subtree Set to true if mutations to not just target, but also target's descendants are to be observed.
attributeOldValue Set to true if attributes is set to true and target's attribute value before the mutation needs to be recorded.
characterDataOldValue Set to true if characterData is set to true and target's data before the mutation needs to be recorded.
attributeFilter Set to an array of attribute local names (without namespace) if not all attribute mutations need to be observed.

MutationRecord

MutationRecord is the object that will be passed to the observer's callback. It has the following properties:

Property Type Description
type String Returns attributes if the mutation was an attribute mutation, characterData if it was a mutation to a CharacterData node, and childList if it was a mutation to the tree of nodes.
target Node Returns the node the mutation affected, depending on the type. For attributes, it is the element whose attribute changed. For characterData, it is the CharacterData node. For childList, it is the node whose children changed.
addedNodes NodeList Return the nodes added. Will be an empty NodeList if no nodes were added.
removedNodes NodeList Return the nodes removed. Will be an empty NodeList if no nodes were removed.
previousSibling Node Return the previous sibling of the added or removed nodes, or null.
nextSibling Node Return the next sibling of the added or removed nodes, or null.
attributeName String Returns the local name of the changed attribute, or null.
attributeNamespace String Returns the namespace of the changed attribute, or null.
oldValue String The return value depends on the type. For attributes, it is the value of the changed attribute before the change. For characterData, it is the data of the changed node before the change. For childList, it is null.

Example usage

The following example was taken from this blog post.

// select the target node
var target = document.querySelector('#some-id');
 
// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});
 
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
 
// pass in the target node, as well as the observer options
observer.observe(target, config);
 
// later, you can stop observing
observer.disconnect();

Additional reading

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 18 -webkit
26
14 (14) 11 15 6.0 -webkit
Feature Android Chrome for Android Firefox Mobile (Gecko) IE  (Windows Phone)  Opera Mobile Safari Mobile
Basic support ? 18 -webkit
26
14.0 (14) 11 (8.1) 15

6 -webkit

7

 

Etiquetas y colaboradores del documento

 Colaboradores en esta página: JordiCruells, alvaropinot
 Última actualización por: JordiCruells,