Knowing when you hear changes in DIV with Javascript

2

Hello, good morning.

I need to compare a change in the DIV1 daughters so I can make a notification. This way I did may not be the best, I'm still learning.

<div class="div1">

           <div class="filha">
           <div class="filha">
           <div class="filha"> assim que adicionado o Js precisa ter como saber </div>
           <div class="filha"> se retirado tbm precisa saber </div>

</div>

var myFunction4 = function() {
	jQuery(".div1").load(" meusite/minhaurl .div1");
};
var myFunction5 = function() {
	filhas = jQuery(".div1 .filha").length;
	//console.log(filhas);
};
setInterval(myFunction4, 10000); 
setInterval(myFunction5, 10000); 
   
Function 4 takes the new data from "div1" and plays it in the correct place. Adding a new "daughter" when it exists. (I do not know if it moves in the DOM)

Function 5 can know exactly the number of child elements in the parent (once added or removed). But how to know how many before?

To be able to compare and be able to notify? Is this the right form?

Is there a better one? Hugs

    
asked by anonymous 16.04.2018 / 14:49

2 answers

3

Very easy, my dear friend. Even more with JQuery!

Follow the walkthrough:

  • Get the html of the first div
  • Get the html of the second div
  • Compare the two
  • Simple like that !!

    Now in practice it would be:

    htmlDiv1 = $("#Div1").html();
    htmlDiv2 = $("#Div2").html();
    
    if (htmlDiv1 != htmlDiv2) {
        // escreva aqui o que acontece quando as duas não são mais iguais.
    }
    
        
    16.04.2018 / 16:02
    2

    To know a change of some component you can use the MutationObserver. Its very simple to use:

    let target = document.getElementById('div-pai');
    
    let observer = new MutationObserver(mutation => {
        // Função vai ser chamada quando tiver inserção ou remoção de algum componente filho.
    });
    
    observer.observe(target, {childList: true});
    

    In this example I put it to note only the changes of child nodes. But you can make some other comments, reference .

        
    16.04.2018 / 19:05