So I’m trying to append a new <li> and increase its ID number by 1 every time so I end up having something like:
<ul id="bxs">
<li id="item-1">1</li>
<li id="item-2">2</li>
<li id="item-3">3</li>
<li id="item-4">4</li>
<li id="item-5">5</li>
<li id="item-6">6</li>
</ul>
This is what my jQuery looks like:
var itemCount = 1;
$(function() {
$("#NewItem").click(function(e) { // NewItem is my button
e.preventDefault();
itemCount++;
var element = $("<li id="item-" + itemCount>" + itemCount + "</li>");
$("#bxs").append(element);
});
});
What I’m I doing wrong? There must be something wrong on where I add the itemCount in the div. I tried this as well: <li id="item-" + itemCount + "> but doesn’t work either.
Can someone guide me please?
Your not concatenating your string properly. You should be using single quotes inside your double quotes. In addition, you can’t set
itemCount = 1if you already have existing items. I suggest settingitemCountdynamically. See example below (and fiddle).Here’s a working fiddle.