Very common scenario using Ajax is to parse the response and create the user interface for end user. I am still new bee to the Ajax and UI words and I only see two choices to create the UI using Ajax (JSON/XML)response ,
- CreateElement() way and go on adding/removing elements dynamically
- Create big string and set innerHTML of some element
Now I have following question:
- Please let me know in case there is something else better choice to do so ?
-
In case I would like to attach event to dynamically created elements what is the better way to do that? I mean in many cases I end up doing something like
<input onclick=”somefunction()” />
Which I really feel bad doing and does cause issue and headaches.
I dont see anything wrong with those two approaches . However setting the innerHTML is better from performance point of view .
In some cases creating the elements dynamically is the only option , you might want to take a look at documentFragment to avoid a lot of reflows ( again for performance reason ) .
ECMA specifies addEventListener to add listeners dynamically to your elements . You would also want to read about event bubbling .