Reputation: 507
I am trying to hide the current element on click but I have many elements of the same id, i want each one to hide on each click.
I normally use php in a foreach loop to append an incremental value on each of the ID's, but in this scenario I cannot do that.
I have this:
<div id="container">
<a href="#" id="hideme">hide me</a>
SOME TEXT
</div>
<div id="container">
<a href="#" id="hideme">hide me</a>
SOME TEXT
</div>
<script type="text/javascript">
$("#hideme").click(function(){
$(this).hide();
});
</script>
Is there any way in jQuery to hide the CURRENT element on click? My current code will only hide the first element.
Example: https://jsfiddle.net/2rnw224b/
Upvotes: 1
Views: 4320
Reputation: 2200
You should not have multiple elements with the same id you should use classes. You simple attach an event listener to all elements with that class name and remove the container when clicked.
Try the example below. I also updated your fiddle.
$('.hideme').click(function(e){
e.preventDefault()
$(this).hide()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<a href="#" class="hideme">hide me</a>
SOME TEXT
</div>
<div class="container">
<a href="#" class="hideme">hide me</a>
SOME TEXT
</div>
<div class="container">
<a href="#" class="hideme">hide me</a>
SOME TEXT
</div>
<div class="container">
<a href="#" class="hideme">hide me</a>
SOME TEXT
</div>
Upvotes: 2
Reputation: 660
$("#container a").click(function(){
$(this).hide();
});
Demo: http://jsfiddle.net/sajadtorkamani/3uygzu7e/
Upvotes: 0