Why is this piece of code not working on Chrome 4.0 but works on FF 3.5. The problem that occurs is the selector $(‘li#node-‘+nodes[i].id +”).append function is not working in chrome but is working fine in firefox. Is there a problem with appending to DOM elements that have been created on runtime in Chrome? Should I use Jquery.live() ?
$.getJSON("/data/all" , function(data){
nodes = data;
len = nodes.length;
for(i=0; i<len; i++){
if(i==0){
// works on FF && Chrome
$('ul#root').append('<li id="node-'+ nodes[i].id +'"><input type="checkbox" name="">'+ nodes[i].name);
// works on FF only
$('li#node-'+nodes[i].id +'').append('<ul id="' + nodes[i].id +'>');
}
else{
...
...
}
Your HTML was invalid, and Chrome did not accept it. Firefox was more lenient in what it allowed. Whenever there are lots of quote openings and closings because of a dynamic value, it’s better to use the object style element creation in jQuery rather than doing it all in a string. The problem is with this line:
The output ul it produces is (notice the missing quote):
For creating complex selectors, it is much better to use string replacement:
To create elements with dynamic attributes, use objects to initialize:
The code below although a little verbose and maybe a little slow is hard to get wrong especially in a language like JavaScript where a missing quote can do havoc as we just witnessed.