I have 2 to 4 links
with same ID
s.
Here is my code:
<a href="#" id="link" class="hallo">Next 1</a>
<a href="#" id="link" class="hallo">Next 2</a>
<a href="#" id="link" class="hallo">Next 3</a>
<a href="#" id="link" class="hallo">Next 4</a>
<a href="#" id="link" class="hallo">Next Article</a>
What I want to achieve is to remove
the link
when its clicked
. For instance: when link
with text Next 2 is clicked I want to remove that link
.
I have tried with this:
$(document).ready(function(){
$('#link').click(function () {
$('#link').closest('a.hallo').remove();
});
});
But It only removes the first link (Next 1) and not other ones.
$(document).ready(function(){
$('#link').click(function () {
$('#link').closest('a.hallo').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="link" class="hallo">Next 1</a>
<a href="#" id="link" class="hallo">Next 2</a>
<a href="#" id="link" class="hallo">Next 3</a>
<a href="#" id="link" class="hallo">Next 4</a>
<a href="#" id="link" class="hallo">Next Article</a>
First of all the id must be unique of the elements in html, secondly, you are targeting the element with id so every time the first element it finds with id link will be picked up, you need to use class attribute and selector.
HTML:
Jquery:
what we have written is that whenever an element with class hallo is clicked remove that element
$(this)
selector will pick the element that currently generated the event which is in our case click event.Snippet: