Mike Mike - 12 days ago 4
HTML Question

Is there an alternative to document.getElementById to access dynamically generated elements?

I have a single page, forward button, back button and a Google map. When clicking forward or back buttons, I don't reload the page, I just change the HTML inside the following tag,

<div id="content"></div>


If a map is available, inside the "content" div will be,

<div id="map" class="map"></div>


Google allows me to access the map with

var map = new google.maps.Map(document.getElementById('map') ...


This works fine for the first time loading the page, but when I change the "content" dynamically, it won't load the map unless I reload the page. I tried changing it to document.querySelector() with the same results.

I know that for certain features like using buttons I can access them using,

$('body').on( 'change', 'div.button', function()...


Is there a way to access/modify a dynamically created element that isn't a button?

Answer

The code which creates a new instance of the map is probably only running once. After you update the #content div, you need to run the code again to instantiate a new map (and, ideally, destroy the previous map).

How are you updating the content dynamically? If you're using jQuery.get() for example, you can supply a callback function which will run after the content has updated. It's here you'd want to load the map.