Reputation: 458
I want to include a div with classname "new-fish" dynamically after the image tag within the section div when I click on post button. the new div included should have new id along with it. Based on the number of clicks so many divs should get added. When i tried with the below code it didnt get appended.
<section class="main-content" id="container">
<div class="oyster"> </div>
<div class="small-fish" id="fish1"> </div>
<div class="medium-fish" id="fish2"> </div>
<div class="large-fish" id="fish3"> </div>
<img src="Assets/Arrow.png" class="right-arrow" alt="arrow" id="rightarrow" />
</section>
<footer> <input type="button" value="Post" class="post-button" /></footer>
/*Jquery */
$('.post-button').on('click',function(e){
//$('#container img:last-child').append('<div class="small-fish"> </div>');
$('#rightarrow').append('<div class="new-fish"> </div>');
});
Upvotes: 0
Views: 1568
Reputation: 13988
use like this...
$(document).ready(function(){
var i=0;
$('.post-button').on('click',function(e){
$('#container').append("<div class='new-fish' id='new-fish"+i+"'>coming </div>");
i++;
});
});
Upvotes: 0
Reputation: 629
You should put your code inside
$(document).ready(function() { ... })
so that it will be called after dom is loaded and the button with class post-button
will exist for sure.
The id rightarrow
references an image and you can't put a div inside an image: what you want to do is append the div to section with id main-content
, and it will be added to end of the section right after the image. Of course, when you add another div, it will be put after the previous one added.
As for the id, you could keep a variable to count the numbers of click.
$(document).ready(function() {
var numberOfClicks = 0;
$('.post-button').on('click',function(e){
numberOfClicks++;
$('#container').append('<div id="appendedDiv'+numberOfClicks+'" class="new-fish"> </div>');
});
});
Upvotes: 2
Reputation: 388326
You cannot append an element an image, you might be looking for is to insert the new-fish
as the next sibling of the image then use .after()
$('#rightarrow').after('<div class="new-fish"> </div>');
Upvotes: 0