-3

I am trying to create a new div with a new ID on each click of the button. Ex: click once, the div will have ID "newItem1" then "newItem2" and so on.

$(document).ready(function() {
    var itemNumber = 1;

    $("#post").click(function(){
        $("body").append('<div id="newItem + itemNumber"><div>');
        itemNumber++;
    });
});
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Mike
  • 1
  • 1
  • 3
  • concat properly like `id="newItem"' + itemNumber+'"` – guradio Jun 16 '17 at 02:22
  • 2
    Possible duplicate of [spaces in ID and putting variable in ID jquery](https://stackoverflow.com/questions/32565178/spaces-in-id-and-putting-variable-in-id-jquery) – guradio Jun 16 '17 at 02:24
  • Possible duplicate of [JavaScript Variable inside string without concatenation - like PHP](https://stackoverflow.com/questions/3304014/javascript-variable-inside-string-without-concatenation-like-php) – Emile Bergeron Jun 16 '17 at 02:26

1 Answers1

1

Just add the variable like the following:

$("body").append('<div id="newItem' + itemNumber.toString() + '"><div>');

Or in ECMAScript 6 like the following:

$("body").append(`<div id="newItem${itemNumber}"><div>`);
OmG
  • 18,337
  • 10
  • 57
  • 90