Nevelle
Nevelle

Reputation: 1

appending with jquery multiple div and each div has its unque ID

How to append multiple id's to show the different boxes. box2, box3 and box4. I was trying to use a for loop to add ascending numbers on the end of the wird box for the Id. Thank you for helping.

$("#go").click(function(){

		$("#boxContainer").append("<div id='box1'></div>");
	

});
#box1 {
  width: 100px;
  height: 100px;
  background-color: blue;
}
#box2 {
  width: 100px;
  height: 100px;
  background-color: grey;
}
#box3 {
  width: 100px;
  height: 100px;
  background-color: orange;
}
#box4 {
  width: 100px;
  height: 100px;
  background-color: green;
}
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
	<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<button id="go">click</button>
<div id="boxContainer">

</div>
</body>
</html>

Upvotes: 0

Views: 91

Answers (2)

Josh Crozier
Josh Crozier

Reputation: 240928

You could set the id based on the number of children elements in the #boxContainer element.

Use the .children() method to get the direct children elements, and then access the length property to get the number of element in the jQuery object.

As of jQuery 1.8, you can create elements using the following syntax:

$("#go").click(function() {
  var id = 'box' + ($("#boxContainer").children().length + 1);
  $("#boxContainer").append($("<div />", { id: id }));
});

Alternatively, you could also use the following:

$("#go").click(function() {
  var id = 'box' + ($("#boxContainer").children().length + 1);
  $("#boxContainer").append('<div id="' + id + '"></div>');
});

Updated Example:

$("#go").click(function() {
  var id = 'box' + ($("#boxContainer").children().length + 1);
  $("#boxContainer").append($("<div />", { id: id }));
});
#box1 {
  width: 100px;
  height: 100px;
  background-color: blue;
}
#box2 {
  width: 100px;
  height: 100px;
  background-color: grey;
}
#box3 {
  width: 100px;
  height: 100px;
  background-color: orange;
}
#box4 {
  width: 100px;
  height: 100px;
  background-color: green;
}
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<button id="go">click</button>
<div id="boxContainer">

</div>

Upvotes: 1

ookie
ookie

Reputation: 138

You can add a simple for loop, in this case will be 0-9.

$("#go").click(function(){
     for (i = 0; i < 10; i++) {


    $("#boxContainer").append("<div id='box'" + i + "></div>");
}

});

Upvotes: 0

Related Questions