Is there any way to detect that an attribute has changed in HTML?

3

I would like to know if you have a javascript check if an attribute of an element has been changed or not.

For example: If I have a input , I put the required attribute on it, and someone goes there and deletes required of that element with Google Chrome Developer Tools , there would be any way, through javascript, to detect this?

Is there an event in javascript that can do something like this?

    
asked by anonymous 13.02.2015 / 13:37

1 answer

6

This can be done using MutationObserver . When creating the MutationObserver you specify a callback that will be called when there is a change in the DOM. Using the observe method you specify which element you want to observe and the types of modifications that you want to be notified about.

An example:

var input = document.getElementById('req');

var observer = new MutationObserver(function(mutations) {
 mutations.forEach(function(mutation) {
     console.log(mutation);
     if(mutation.type == "attributes" && mutation.attributeName == "required") {
         console.log(mutation);
         alert("Atributo required modificado!");
     }
 });
});

observer.observe(input, {attributes: true});
Inspecione o elemento e modifique/remova o atributo "required" do input abaixo para testar.<br /><br />
<input type="text" id="req" required />

Remembering that using this for validation is not a good idea because the client can simply disable javascript, modify your code, remove it, etc.     

13.02.2015 / 14:36