views:

50

answers:

2

This is related to an earlier question. I try to append HTML DOM returned in an AJAX response to an existing DIV. I see all the text, but it seems all markup such as bold, italic, etc is lost.

My AJAX (XML) data is like so:

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

My jQuery code does this:

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

Attempting to do .html() on the cloned contents throws an exception: TypeError: Cannot call method 'replace' of undefined.

I am a little surprised that it is so excruciatingly hard to do this with jQuery. Am I doing something too far off the track?

A: 

Seems the trouble is for jQuery to find tags/nodes which are named different from allowed tags. That said, your XML is not well formatted either as it has both a node and text within contents.

This is not nice, but it will work:

$("#eventDiv").append($(":first-child", data).parent().html());

The <content> tag will be included, but is ignored by the browser.

Mikael Svenson
A: 

Looks like jQuery does not provide an easy way for what I am trying to do. To recap, my server returns the following data in ajax response:

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

I would like to display the stuff inside the contents tag in a div. My JS code handles this in the ajax success handler as follows:

var jData = $( data );

I have a div with id eventDiv where I need to display the contents of the event. I was hoping to do it with:

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

but this was causing all markup to be lost, resulting in just the text.

The following based on XMLSerializer works for me (will not work for IE):

var contents = jData.find( "contents" );

if( contents != null )
{
    var serializer = new XMLSerializer ();
    $( contents ).contents().each( function( index, value ) 
    {
        var cloned = $( value ).clone();
        $( "#eventDiv" ).append( serializer.serializeToString( cloned[ 0 ] ) );
    });
}