Imagine that you have a webpage that has a lot of elements that you want to access, but you don’t want to create an ID for each one and use a different instruction to access them. For that, you can use the power of jQuery to detect which element is clicked with a few lines of code. The event is linked to the element action, for this you can use the event in the function to get the element.
This blog post provides the information needed to detect which element is clicked using jQuery.
Suppose you have the code below in your html page and you want to detect which button you clicked.
<div class="col-md-12 text-center mb-1">
<h3>Make a Gift</h3>
<button type="button" class="btn btn-primary">$10</button>
<button type="button" class="btn btn-primary">$25</button>
<button type="button" class="btn btn-primary">$60</button>
<button type="button" class="btn btn-primary">$160</button>
<button type="button" class="btn btn-primary">$400</button>
</div>
First of all, you must have the jQuery library and it must be placed before your jQuery code. Here is the way to add the jQuery library:
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
Below is the jQuery code to detect the button you clicked.
$(function(){
$("button").click(function(event){
console.log(event.currentTarget);
});
});
Another way to detect the element you clicked is to use the Target method. Below is the jQuery code to detect which h3 you clicked on.
$(()=>{
$("h3").click(function(event){
console.log(event.target);
});
});
Now to remove the button you clicked, use the jQuery remove method to do so.
$(()=>{
$("button").click(function(event){
event.currentTarget.remove();
});
});
Video to show you how to remove the button you clicked using jQuery
Note: You can find a copy of the full code I used in this blog post on my GitHub page (link is in my bookmark page).
What To Read Next
- How to install XAMPP in Windows 10
- Embed youtube playlist on webpage
- How to set CSS styles with jQuery
- When to create internal or external links in html
- How to download the entire file in a website folder
If you like the content of this post or if it has been useful to you, please consider sharing it on your social media and follow me on Facebook and Twitter for more exclusive content.