Julian Gauche
Julian Gauche

Reputation: 31

How do you add an element into the last place inside a DIV with jQuery?

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

Answers (4)

Jonathon Bolster
Jonathon Bolster

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

Bhanu Prakash Pandey
Bhanu Prakash Pandey

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

J&#243;n Trausti Arason
J&#243;n Trausti Arason

Reputation: 4698

You can use jQuery's append method - http://api.jquery.com/append/

$('#a').append('<div id="a4">...</div>');

Upvotes: 1

Nick Craver
Nick Craver

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

Related Questions