append

jQuery append closing tags automatically

Posted on: November 8th, 2012 by taff 1 Comment

 

Today I came across some automagicalness whilst using jQuery's append method to append HTML to a container element. I wanted to add an opening p tag, then loop through some XML data, then close the p tag, some thing like this:

$("#container").append("

");
$(this).children().each(function(){
var tagName=this.tagName;
var val=$(this).text();
$("#container").append("<strong>"+tagName+"</strong> "+val+"
");
});
$("#container").append("

");

which was generating Markup like:


<strong>description</strong>
Value 1

<strong>range</strong>
0 - 35

<strong>score</strong>
0

<strong>description</strong>
Value 2

<strong>range</strong>
0 - 15

<strong>score</strong>
0

As you can see jQuery's append method is closing the <p> tag immediately. Normally this would be good to ensure a sound HTML structure, but in our case unfortunately not.

jQuery Append Workaround to avoid tags closing themselves automatically

This is the idea I used to solve the problem. my version had a loop within a loop, but the following lines demonstrate how to use get around jQuery closing tags automagically.

var pTag = $("

");
var pContents ="";

$(this).children().each(function(){
var tagName=this.tagName;
var val=$(this).text();
pContents+="<strong>"+tagName+"</strong> "+val+"
");
});

pTag.append(pContents);
$("#search_results").append(pTag);

which will generate


<strong>description</strong>
Value 1

<strong>range</strong>
0 - 35

<strong>score</strong>
0

<strong>description</strong>
Value 2

<strong>range</strong>
0 - 15

<strong>score</strong>
0

That last <br> in the loop shouldn't really be there. The simplest way would be to check the length of the collection. I will cover this in another post soon. I hope this post helps if you are having trouble with the jQuery append method.