views:

68

answers:

1
+2  Q: 

jQuery append DOM

All the examples of jQuery.append() seem to take an html string and append it to a container. I have a slightly different use case. My server returns me an XML that contains HTML text to be displayed, something like:

<event source="foo">
    <contents>
        <h1>This is an event</h1>
        This is the body of the event
    </contents>
</event>

I have a div where this content needs to be displayed.

My JS currently does the following:

  1. Loads up the XML data into jQuery in the $.ajax() success handler:

    var jData = $( data );

  2. Find the contents tag and tries to add its children to the div that is supposed to display the event:

    var contents = jData.find( "contents" );
    if( contents != null )
    {
        $( contents ).children().each( function( index, value ) 
        {
         $( "#eventDiv" ).append( $( value ) );
        });
    }
    

The append() call fails with Uncaught Error: WRONG_DOCUMENT_ERR: DOM Exception 4 on Chrome. The debugger shows value to be a DOM Element object and $( value ) to be an Object that contains the Element.

Any help will be appreciated.

Thanks. -Raj

+2  A: 

You can't append nodes that belong to one DOM tree to another document.

Try to clone them:

$("#eventDiv").append( jData.find("contents").children().clone() );

or simply use their textual representation to have them re-created:

$("#eventDiv").append( jData.find("contents").html() );
Tomalak
Thanks. Clone() seems to move me forward. Still, calling html() causes error: $( child ).clone().html(): TypeError: Cannot call method 'replace' of undefined
actually I use contents().clone() which also includes text nodes.
@raj: The `.html()` fails because you are dealing with an XML document here, and jQuery is not 100% fitted to deal with XML in all cases.
Tomalak
I am much futher along. The problem I face now is warrants a new question. Thanks for your help, Tomalak!
@raj: You're welcome. If you have a chance to change how the server sends the response, just XML-encode everything within `<contents>` and do `$("#eventDiv").append( jData.find("contents").text() );`.
Tomalak