In order to know whether the jQuery selector selected any element or not, Here 2 methods are discussed and these are mostly used methods.
Example-1: In this example, Selector searches for <p> element. This example uses the length property to check If something is selected or not. In this case <p> element is found.
html
Output:
html
Output:
html
Output:
<!DOCTYPE html>
<html>
<head>
<title>
JQuery |
check if a selector matches something.
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;" id="body">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p>
A computer science portal for geeks.
</p>
<button onclick="gfg_Run()">
check
</button>
<p id="GFG_DOWN"
style="color:green;
font-size: 20px;">
</p>
<script>
var el_down =
document.getElementById("GFG_DOWN");
var str = '';
function gfg_Run() {
if ($("p").length) {
str = "Something Selected";
} else {
str = "Nothing Selected";
}
el_down.innerHTML = str;
}
</script>
</body>
</html>
-
Before clicking on the button:
-
After clicking on the button:
<!DOCTYPE html>
<html>
<head>
<title>
JQuery |
check if a selector matches something.
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;" id="body">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p>
A computer science portal for geeks.
</p>
<button onclick="gfg_Run()">
check
</button>
<p id="GFG_DOWN"
style="color:green;
font-size: 20px;">
</p>
<script>
var el_down =
document.getElementById("GFG_DOWN");
var str = '';
function gfg_Run() {
if ($("a").length) {
str = "Something Selected";
} else {
str = "Nothing Selected";
}
el_down.innerHTML = str;
}
</script>
</body>
</html>
-
Before clicking on the button:
-
After clicking on the button:
<!DOCTYPE html>
<html>
<head>
<title>
JQuery |
check if a selector matches something.
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;" id="body">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p>
A computer science portal for geeks.
</p>
<button onclick="gfg_Run()">
check
</button>
<p id="GFG_DOWN"
style="color:green;
font-size: 20px;">
</p>
<script>
var el_down =
document.getElementById("GFG_DOWN");
var str = '';
jQuery.fn.exists = function() {
return this.length > 0;
}
function gfg_Run() {
if ($("button").exists()) {
str = "Something Selected";
} else {
str = "Nothing Selected";
}
el_down.innerHTML = str;
}
</script>
</body>
</html>
-
Before clicking on the button:
-
After clicking on the button: