Reputation: 2800
I have the following html
<div class="someClass">
Some text
</div>
<div class="someClass">
Some other text
</div>
<div class="add>
<img src="someImage.jpg">
</div>
Now I'd like to append another div after a click on the add image - but only after the last div with the class "someClass".
If I use the following jQuery it will be appended after each someClass element, so multiple times.
$(".add img").live("click", function() {
$(".containerFooter").after("<div class='someClass'>test</div>");
});
Is there a way to only append it after the last div with the someClass attribute?
Upvotes: 4
Views: 1915
Reputation: 4911
Sorry, dint read the question completely in first attempt, updated the ans!
Also your html has a typo , its make it
$(".someClass").last() //-> selects your last div with id = someClass
.after("<div class='someClass'>test</div>");//-> place the html after the selected div
Actual code below
$(".add").live("click", function(){
$(".someClass").last().after("<div class='someClass'>test</div>");
});
Upvotes: 1
Reputation: 28645
You are looking for the :last
selector:
$(".someClass:last").after("<div class='someClass'>test</div>");
Upvotes: 6
Reputation: 27482
There may be an easier way, but a jquery class returns an array of applicable objects. So you can find the last such object, create a new jquery object from it, and then operate on that.
<html><title>JQuery Play</title>
<h1>JQuery Play</h1>
<script src="jquery-1.4.1.js" type="text/javascript" ></script>
<script type="text/javascript">
function add()
{
var x=$(".someClass");
$(x[x.length-1]).after("Added text");
}
</script>
<div class="someClass">
Some text
</div>
<div class="someClass">
Some other text
</div>
<div class="add">
<button onclick="add()">Add</button>
</div>
</html>
Upvotes: 0
Reputation: 2812
$(".add img").live("click", function() {
$(".someClass:last").after("<div class='someClass'>test</div>");
});
Upvotes: 1
Reputation: 7455
Use:
$(".someClass").last().append("<div class='someClass'>test</div>");
Upvotes: 1
Reputation: 11264
$('.someClass').last()
OR
$('.someClass:last')
will give you last element of class someclass
Upvotes: 2