Reputation: 9066
I have a main document div to add some html element through variable "str"
<div id='documentDiv'></div>
I have a functionality which will add some html element to my #documentDiv
.
var str="<div class='customElement'></div><a href='' onclick='append(event);'>append</a>"
And I have a functionality to append str
to documentDiv
as many time I want:
$('#documentDiv').append(str);
after appending two times I have the same structure appended twice inside my documentDiv element
<div id='documentDiv'>
<div class='customElement'></div><a href='' onclick='append(event);'>append</a> // want to append some text to respective .customElement div
<div class='customElement'></div><a href='' onclick='append(event);'>append</a>
</div>
My problem is with onclick ,i want to append something inside the respective div under customElement
class.But with onClick ,it always gets appended to the first div.How can i get respective div element using jquery?
function append(event){
$('.customElement').append("some text");
}
Upvotes: 1
Views: 115
Reputation: 171
Maybe this could help you: Without a-tag:
$('.customElement').bind('click',function(){
$(this).append("some text");
});
or with a-tag:
$('.customElement a').bind('click',function(){
$(this).parent().append("some text");
});
Upvotes: 2
Reputation: 15293
Since you are adding your elements dynamically you should delegate the events by adding the on
method to the parent element.
Here is an example.
function append(event){
$(this).prev().append("some text");
event.preventDevault();
}
$('#documentDiv').on('click', 'a', append);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id='documentDiv'>
<div class='customElement'></div><a href='#'>append</a>
<div class='customElement'></div><a href='#'>append</a>
</div>
Upvotes: 0
Reputation: 2823
I believe you want to use this.
function append(event){
$(this).append("some text");
}
Upvotes: 1