views:

99

answers:

2

I'm parsing an XML file and trying to return the output to a div. However, for some reason .append() doesn't seem to be generating the correct HTML output.

Here is the JQuery snippet:

var list = $('<div class="response">').appendTo(this);
list.append('<ul>');

$('item',data).each(function(i){
    var dow = $(this).find("day").text();
    var high = $(this).find("high").text();
    var low = $(this).find("low").text();
    var conditions = $(this).find("conditions").text();
    var icon = $(this).find("icon").text();

    list.append('<li style="background: url(' + icon + '.gif) no-repeat;"><b>' + dow + '</b> - ' + conditions + ' (Hi: ' + high + ', Low: ' + low + ')</li>');         
});

The HTML this produces is as follows:

<div class="response"></div>
<ul></ul>
    <li style="background: url(partlycloudy.gif) no-repeat;"><b>Wednesday</b> - Partly Cloudy (Hi: 50, Low: 43)</li>
    <li style="background: url(partlycloudy.gif) no-repeat;"><b>Thursday</b> - Partly Cloudy (Hi: 59, Low: 34)</li>
    <li style="background: url(partlycloudy.gif) no-repeat;"><b>Friday</b> - Partly Cloudy (Hi: 45, Low: 25)</li>
    <li style="background: url(chancesnow.gif) no-repeat;"><b>Saturday</b> - Chance of Snow (Hi: 36, Low: 22)</li>
    <li style="background: url(partlycloudy.gif) no-repeat;"><b>Sunday</b> - Partly Cloudy (Hi: 36, Low: 20)</li>
    <li style="background: url(partlycloudy.gif) no-repeat;"><b>Monday</b> - Partly Cloudy (Hi: 34, Low: 20)</li>

Any idea why the tags are being closed prematurely? I'm at a bit of a loss. If there is another way I should be doing this I'd appreciate you pointing me in the right direction.

Thanks in advance!

+1  A: 

When you append the UL, it appends a fully formed and closed element. It is better to build up the entire HTML as a string and then append the whole string at once.

Geoff
+2  A: 

append() is not a string append. It is working on the live DOM as you go. When you append a <ul>, it automatically adds the closing tag. Whatever you add to the markup after that comes later.

Instead, try this.

var list = $('<div class="response">').appendTo(this);
var ul = $('<ul></ul>');

$('item',data).each(function(i){
    var dow = $(this).find("day").text();
    var high = $(this).find("high").text();
    var low = $(this).find("low").text();
    var conditions = $(this).find("conditions").text();
    var icon = $(this).find("icon").text();

    ul.append('<li style="background: url(' + icon + '.gif) no-repeat;"><b>' + dow + '</b> - ' + conditions + ' (Hi: ' + high + ', Low: ' + low + ')</li>');          
});
list.append(ul);
Chetan Sastry
Worked perfectly. Thanks Chetan!
Russell C.