1

When I'm using this code:

<script type="text/javascript">
$(document).ready(function() {

$.ajax({
type: "GET",
url: "nyhederlang.xml",
dataType: "xml",
success: parseXml,
error: function(){alert("Error: Something went wrong");}
 });
 });

 function parseXml(xml)
 {
 //print the title and the description
 $(xml).find("article").each(function()
 {
 $("#output").append("<div>");
  $("#output").append("<b>" + $(this).find("title").text() + ":</b> <br />");
  $("#output").append($(this).find("paragraphs").text());
   $("#output").append("</div>");
  });
  }
  </script>

I get both div and /div in the beginning of #output.

Why isn't /div placed at the end of #output?

This is what it looks like:

<div id="output">
<div></div>
<b>Some title text</b>
.
.
.
.
.

3 Answers 3

8
$("#output").append("<div>");

doesn't append just "<div>" but a well formed (closed ) html element. That is a complete div.

The solution is to build your complete HTML and then append it :

var html = "<div>";
html += "<b>" + $(this).find("title").text() + ":</b> <br />";
html += $(this).find("paragraphs").text();
html += "</div>";
$("#output").append(html);

You could also append to the first appended div its content but, as is pointed by Ian, it's always more efficient to minimize the number of appendings.

Sign up to request clarification or add additional context in comments.

4 Comments

Appending to the DOM is also time consuming so it's more efficient to do it this way.
I'm sorry. I don't understand what you are telling me: "build your complete HTML"
He means exactly the example he posted, you build the HTML in a string, then you append it only once at the end
As you can't append something like "</html>" because anything you add is interpreted as a document fragment, you must build the complete HTML as in my answer and append it in one go.
0

You can't append a partial <div> tag.

jQuery will close the tag for your automatically when you append it, so the following append will therefore be placed after the intial <div>. And the final </div> you append will be another empty div after it.

What you should do is build up the whole string, and append it in a single .append() call.

$("#output").append("<div>
                   +"<b>" + $(this).find("title").text() + ":</b> <br />"
                   +$(this).find("paragraphs").text()
                   +"</div>");

Comments

0

Instead of appending each element; add it to a string then append that string. Ex:

var html = "";
html += "<div>"
html += "<b>" + $(this).find("title").text() + ":</b> <br />";
html += $(this).find("paragraphs").text();
html += "</div>";

$("#output").append(html);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.