Search code examples
javascriptjqueryobject-literal

Object Literal: Dynamic DOM not accessible


I haven't fully grasp the fundamentals of Object Literal in Javascript, so here's an example of my issue. I have created an AJAX function post() that returns <div id="foo"></div> inside <div id=test></div> to simulate my problem.

var a = {
    static: $('#test'),
    dynamic: $('#foo'),
    test: {
        load: function(){
            post().done(function(r){
                a.static.html(r.testing)
            })
         }
    }
}

var b = {
    test1: function(m){
        a.static.html(m)
    },
    test2: function(m){
        a.dynamic.html(m)
    }
}

What I don't understand is this:

  1. b.test1('Hello') will write to HTML accordingly, because the initial HTML file contains #test. This is totally understandable.

  2. b.test2('Hello') will not write, because I don't know why, and here is where I need some explanation.

Here's the fiddle for your convenience: http://jsfiddle.net/tfYGR/2/


Solution

  • Because the expression dynamic: $('#foo') is evaluated at the beginning of the script execution when the element with id foo is not created so $('#foo') will return an empty jQuery object.

    The #foo element is created only when the test1 method is called.

    A possible solution is to store the dynamic element selector in a.dynamic instead of trying to store the jQuery object like

    dynamic: '#foo'
    

    then

    $(a.dynamic).html(m)
    

    Demo: Fiddle

    In the above case the selector #foo is not evaluated till the test2 is called, by that time test1 has added the target element to the dom