Reputation: 31
If I have a div like this:
<div id="a">
<div id="a1">...</div>
<div id="a2">...</div>
<div id="a3">...</div>
</div>
How do I add another div into the last position inside #a
using jQuery?
<div id="a4">...</div>
so that it becomes this:
<div id="a">
<div id="a1">...</div>
<div id="a2">...</div>
<div id="a3">...</div>
<div id="a4">...</div>
</div>
Upvotes: 3
Views: 3530
Reputation: 15961
Here's another alternative:
$("#a").append(function() {
var nextId = $(this).children().length + 1;
return $('<div/>')
.attr('id','a' + nextId)
.html('New id: a' + nextId);
});
This will check how many divs you have an add a new one with the correct ID
Example: http://jsfiddle.net/jonathon/2h9aZ/
Upvotes: 0
Reputation: 3785
try this
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery-latest.js"></script>
<script type="text/javascript">
$( init );
function init() {
var newPara = $( "<div id='a4'>...</div>" );
$('#a').prepend( newPara );
}
</script>
</head>
<body>
<div id="a">
<div id="a1">...</div>
<div id="a2">...</div>
<div id="a3">...</div>
</div>
</body>
</html>
Upvotes: 2
Reputation: 4698
You can use jQuery's append method - http://api.jquery.com/append/
$('#a').append('<div id="a4">...</div>');
Upvotes: 1
Reputation: 630637
Just use .append()
to stick it at the end:
$("#a").append('<div id="a4">...</div>');
If a4
already exists, or you're creating it, you can also use .appendTo()
the other way around:
$("#a4").appendTo("#a");
//or if creating...
$('<div id="a4">...</div>').appendTo("#a");
Upvotes: 6