Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to check the element type of an event target with jQuery?
To check the element type of an event target, we use the is() method. The is() method checks the current matched set of elements against a selector and returns true if at least one of these elements matches the given arguments.
Example
You can try to run the following code to check the element type ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("ul").click(function(event) {
var target = $(event.target);
if (target.is("li")) {
alert("Element is 'li'");
} else if (target.is("ul")) {
alert("Element is 'ul'");
} else {
alert("Element is something else");
}
});
});
</script>
</head>
<body>
<p>Click below to find out which element type was clicked</p>
<ul>
<li>India</li>
<li>US</li>
<li>UK</li>
</ul>
</body>
</html>
In this example, when you click on any list item (li), it will show an alert saying "Element is 'li'". If you click on the ul element itself, it will show "Element is 'ul'". The event.target property refers to the actual element that triggered the event, and the is() method checks if that element matches the specified selector.
Conclusion
The is() method provides a simple way to check the element type of an event target in jQuery. This technique is particularly useful when dealing with event delegation and determining which specific element was interacted with.
