I have a loop and in this loop I will add li element and after that I should add a element inside li , but when I wrote this code, the a element will add to all li elements.
var toolbarArray = new Array("Home", "About", "Contact");
var ceItem = $('#toolbar').append('<ul></ul>').find('ul');
var ceLiItem;
for (i=0; i<toolbarArray.length; i++) {
ceLiItem = ceItem.append('<li></li>').find('li');
ceLiItem.append('<a>'+toolbarArray[i]+'</a>');
}
this is result: http://jsfiddle.net/SKPxE/
The structure of your code can be re-arranged a bit: http://jsfiddle.net/SKPxE/4/
declaring just one
varper scope makes things a little neater (jsLint).you can use
$.each()to iterate an array (your method is fine too, but there will be times when the jQ version will come in handyyour link will most likely be more than just text, so the code above prepares you for that (note the
hrefattribute)when you create an element with jquery,
$('<li></li>'), you do not need to use.find()to grab it, it’s already thereedit: see Anthony’s post on
.appendTo()