I am trying to append li elements coming from a php file with JQuery. Problem is that the html code needs to be seperately appended to different html IDs according to the key value. Unfortunately as I understood append() can only append correct html with all elements closed. Otherwise it will automatically close the tags. The following code will NOT work as dval contains code like <div><li class="some">Some value</li> and append() will make <div><li class="some">Some value</li></div> out of it. So I was wondering whether there is another way, maybe a function other than append() to be able to append html parts?
EDIT:
This is my Jquery:
$.getJSON("../ajax.php", function(data)
{
$.each(obj, function(key,val)
{
$.each(obj[key], function(key, dval)
{
if(key == "text")
{
$("#" + key).append(dval);
}
})
});
});
This is my PHP:
$json_arr = $json_arr."[";
if($counter % 2 == 0)
{
$arr[0] = preg_replace('#<td class="some">(.*?)</td>#', '<li id="1234"><span class="some">$1</span>', $ja[0]);
}
else $ja[0] = preg_replace('#<td class="some">(.*?)</td>#', '<span class="some2">$1</span><div class="somediv"></div></li>', $ja[0]);
$json->id = $closest_key; // Closest key is the ID of an existing li element which is the closest to the current word
$json->text = $ja[0];
$json_arr = $json_arr.'{"id":"'.$json->id.'", "text":"'.addslashes($json->text).'"},';
$json_arr = substr($json_arr,0,-1);
$json_arr = $json_arr."]";
echo(json_encode($json_arr));
Now if counter is even <li id="1234"><span class="some">$1</span> should be appended to $closest_key, if it is odd then <span class="some2">$1</span><div class="somediv"></div></li> should be appended.
Its not realy jquery that is adding the closing tag, its your browser. In order to render a webpage it needs to have a valid HTML DOM and it will try to fix errors for you.
What you are doing will be very slow with a large obj, because after every append the entire page will be recreated (meaning every width/height/position must be recalculated). (google javascript reflow / repaint)
The best thing to do is to create the full HTML strings first and then append it.