-4

I am working on a reflection of part of my website. This is the relevant HTML:

<div id = "original">
    <img src = "picture.png" alt = "A picture" id = "picture">
    <p id = "text">Some text</p>
</div>
<div id = "reflection"></div>

My Idea is copying the content of div#original to div#reflection like this:

<script>
    function reflect()
    {
        var original = document.getElementById("original");
        var reflection = document.getElementById("reflection");
        reflection.innerHTML = original.innerHTML;
    }
</script>

I am aware, that this will make the HTML invalid, in the whole project I iterate through the elements copied and set the IDs to not have that side effect. I just thought that this would be unnecessary to include here.

The problem I have is that the HTML I want to reflect is dynamic, so it may change. Then the reflection is wrong. I have searched for an event handler for this, but haven't found one. The only one near I found was onchange, but apparently this listens to changes in the attributes, not the child elements. Is there another one for this, or did I just use onchange wrong?

Thank you for your help!
GeF

I am aware that I could add onchange to every element, but this seemed not good style to me.

GeF
  • 70
  • 6

1 Answers1

1

The simplest thing you can do is add a callback to reflect() every time you change the contents of the #original.

If this is not an option, you can look into a MutationObserver (documetation), as suggested here: Is there a JavaScript/jQuery DOM change listener?

Community
  • 1
  • 1
blgt
  • 8,135
  • 1
  • 25
  • 28