PrototypeJS: how to select dynamically created elements?


The website is using Prototype JS library.

After page loads, it immediately executes Ajax request, which pulls out and displays more elements for the page.

I need to be able to select those dynamically created elements and hide them with .hide() method.

I have tried to select and hide them using document.observe('dom:loaded', function() { $('my-new-dynamic-element').hide(); }), but this code does not 'see' the dynamic elements.

I saw Prototype has .on() method, but I am not sure which Event should I specify in my case? I tried Event 'load', but no success.

I would appreciate any tips how I could solve this problem.

UPDATE: I need to accomplish this in the Magento CMS backend, so I cannot, or better - I do not want to modify original Magento javascript codes and ajax request HTML output. So I need to accomplish this by adding extra custom Javascript code which is using PrototypeJS selectors on dynamically published elements. They need to be hidden, and never shown again. I hope there is a simple couple of lines solution for this.

PS: I am trying to hide some address elements in Magento Admin -> "Create New Order" page, where all the customer contact data is pulled with ajax request after the main page is loaded. But I don't think this information is important for the problem description.

If you're planning to show them again later, you could add the 'style="display:none"' to whatever creates the HTML you're inserting (the function behind /myurl, in other words), then you can simply show these elements later in a deferred listener, such as the ones created by the on() method.

// /myurl => '<input type="text" class="foo" style="display:none">'

// later, in the combined page
document.on('click', '.some-control', function(evt, elm){

That's a fairly broad selector, you could do something much more specific using next and previous or an id selector instead. The point of the on() method is that the contents of its closure are not evaluated until the event happens, so you can rely on everything that matches the selector being found when it is evaluated, whether it was there at page load or was added later.

If you just want to hide the things that are being added to the page, and you want a completely agnostic method, you can try this:

document.on('DOMSubtreeModified', function(evt){
    if(elm.visible()) elm.hide();

That will fire each time the page is modified, so you can test and hide things as they are added if they match your inner selector.