Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding generated content to jQuery object which is not bound to the DOM fails

I am trying to dynamically append an HTML-snippet to an existing Element with .append.

Somehow, the HTML String which was created by the script is not appended to the element.

The element which is appended to is not hooked into the DOM at the moment when the snippet is appended.

All of it is encapsulated in a JavaScript function. Here is the code:

append_content = function() {
    var elem = $('<li><div>some text</div></li>');
    var somecontent = get_content();  // returns a string: '<div>xx</div>'
    elem.append('<div>bleh1</div>');
    elem.append(somecontent);
    elem.append('<div>bleh2</div>');
    console.log(elem);
    return elem;
}

The log contains all items correctly, like:

<li>
    <div>some text</div>
    <div>bleh1</div>
    <div>xx</div>
    <div>bleh2</div>
</li>

But when im hooking the elem to the DOM later on, the content of the function call is gone. I.e. it is not visible in the computed source (neither in FireBug nor Chrome development tools).

It looks like this:

<li>
    <div>some text</div>
    <div>bleh1</div>
    <div>bleh2</div>
</li>

I am almost convinced that I have some scope issues or something like that here, but I don't get it. There is no error message in the console. Any advice?

Update

Indeed, this was a self-made problem. Striipng down the code for an examle to post here made me realize that i called a similar function wihtout the function call mentioned above - silly me. Thanks for all the comments and help.

like image 835
David Avatar asked May 01 '12 10:05

David


1 Answers

It looks correct to me - I'd check the output of the get_content() method to ensure it is in fact returning valid html. Check it using alert("somecontent") as well as console - console.log only writes out the first line of XML in firebug - not sure about chrome...

like image 57
reach4thelasers Avatar answered Nov 10 '22 06:11

reach4thelasers