jQuery Closing Open Tags

8.3k Views Asked by At

While trying to parse an xml file into table format, jQuery keeps closing my opening <tr> tag. Is there a work around for this?

<script type="text/javascript">
    $(document).ready(function(){
    $.ajax({
            type: "GET",
            url: "sample-data.xml",
            dataType: "xml",
            success: parseXml
        });
    }); 

    function parseXml(xml)
    {
      $(xml).find("user").each(function()
      {  
        var id = "#sortable";  
            $(id).append("<tr>");
            $(id).append("<td>" + $(this).find("name").text() + "</td>");
            $(id).append("</tr>");

      });
    }
</script>

<table id="table" class="tablesorter">
    <thead>
      <tr>
        <th>test</th>
      </tr>
    </thead>
    <tbody id="sortable">

    </tbody>
</table>

This is how the markup is being outputted:

 <tr></tr>
 <td>data</td>
4

There are 4 best solutions below

2
On BEST ANSWER

Yeah, jQuery doesn't really work that. Try this:

function parseXml(xml)
{
  $(xml).find("user").each(function()
  {  
    var id = "#sortable";  
        $(id).append('<tr></tr>');
        $(id).find('tr:last').html("<td>" + $(this).find("name").text() + "</td>");

  });
}
1
On

Simply call 1 append instead of multiple appends.

Change this part:

        $(id).append("<tr>");
        $(id).append("<td>" + $(this).find("name").text() + "</td>");
        $(id).append("</tr>");

to this:

        $(id).append("<tr><td>" + $(this).find("name").text() + "</td></tr>");
0
On

I'd suggest to not use append on the loop. Instead, output it outside the loop.

var id = $("#sortable");
var html = '';

  $(xml).find("user").each(function()
  {  

    html += '<tr>';
      html += '<td>';
          html += $(this).find("name").text( );
      html += '</td>';
    html += '</tr>';   
  });

  id.append(html);

In cases that you're going to use $(this), many times inside the loop, like for age, gender etc, I suggest you assign a variable to $(this) instead of calling $(this) over and over again.

P.S I didn't test that code, just want to suggest something... but hope it works. Cheers ^^

0
On

I don't think that jQuery is the culprit here.

When you call append("<tr>"), what do you want it to do? Answer: You want it to modify the DOM per your specification. But, the DOM is a data-structure, not a string. You cannot add an "unclosed" element to the DOM, so all elements are inherently closed at the time they are added.

As a result, the subsequent append("<td>...</td>") is adding the TD element after the <tr> rather than inside of it. Furthermore, any attempt to append("</tr>") is simply ignored since it would be rather nonsensical given the handling of append("<tr>").