1

I want to create a new div element, with unique id from the latest array that i push every i click a create button , but it seem my code not working, here is my code below :

$(document).ready(function(){
  var arr = [];
  counter = 0;
   
  
  $('#newDiv').on('click', function(){
    $('.container').append('<div class="image">hallo</div');
    counter ++;
    arr.push(counter);
    $('.image').attr('id',arr[arr.length-1]);  
  })
})
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
  <div class="container"></div>
  <button id="newDiv">create new div</button>
</body>
</html>
Riantori
  • 317
  • 1
  • 4
  • 14
  • Just combine [Get the last item in an array](https://stackoverflow.com/q/3216013/215552) and [jQuery create new div with ID?](https://stackoverflow.com/q/5314537/215552). – Heretic Monkey Feb 17 '18 at 22:08

3 Answers3

2

On each click you are setting id of each image element to last element in array, instead you can do something like this.

let arr = [], counter = 0;

$('#newDiv').on('click', function() {
  arr.push(counter++)
  const img = $('<div />', {
    'class': 'image',
    'id': arr.slice(-1)
  }).text('hallo');
  $('.container').append(img)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
<button id="newDiv">create new div</button>

Or you can first push counter to array and then take last element for array with slice and use it as id.

let arr = [], counter = 0;

$('#newDiv').on('click', function() {
  arr.push(counter++)
  const img = $(`<div class="image" id=${arr.slice(-1)}>hallo</div>`)
  $('.container').append(img)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
<button id="newDiv">create new div</button>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • Hi @Nenad your answer can be a solution if i only want to get the unique id, but i only want the unique id came from the latest array that i push, it can be not from the counter.. – Riantori Feb 17 '18 at 21:54
  • 1
    I updated my answer, now id is always last element in array. – Nenad Vracar Feb 17 '18 at 21:56
  • 1
    @NenadVracar Whoa, I learned something new today! I was puzzled by that syntax I've never seen before and had to [**look it up**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals). – user9263373 Feb 17 '18 at 22:07
1

First when you use classe query selector it would add the id to every element with that class so here is a work around you can use :

Add the add on the appending part

$(document).ready(function(){
  var arr = [];
  counter = 0;
   
  
  $('#newDiv').on('click', function(){
    counter ++;
    arr.push(counter);
    $('.container').append('<div id='+(arr.length-1)+' class="image">hallo '+(arr.length-1)+'</div');
  })
})
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
  <div class="container"></div>
  <button id="newDiv">create new div</button>
</body>
</html>
M0ns1f
  • 2,705
  • 3
  • 15
  • 25
1

Your original code is selecting all div with the image class and updating them all with the latest number.

I suggest creating the div adding the number to the new div only and then appending it to the container.

Please review the updated code below:

$(document).ready(function() {
  var arr = [];
  counter = 0;


  $('#newDiv').on('click', function() {
    counter++;
    arr.push(counter);

    // Create div
    $('<div class="image"></div').text('hallo')
      // Add ID attribute
      .attr('id', arr[arr.length - 1])
      // Apend new div to container
      .appendTo('.container');
    
  })
})
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://code.jquery.com/jquery-1.9.1.js"></script>
</head>

<body>
  <div class="container"></div>
  <button id="newDiv">create new div</button>
</body>

</html>
Pablo
  • 5,897
  • 7
  • 34
  • 51
  • 2
    Don't forget that you can pass initial attributes via an object, e.g. `$('
    ', { text: 'hallo', id: 'foo' })`.
    – Alnitak Feb 17 '18 at 21:57