Introduction
Whenever we query an element using a selector, it is necessary to check whether that element exists or not, particularly for an element which is created dynamically. This blog explains how to check if an element exists in DOM or not, using jQuery.
Check the element exist
When you use the selector, it always returns the wrapped set. The result can be empty if the element is not there. The best way to find if the element exists or not is using the length property of the element. If the element does not exist, the value of its length will be zero.
Demo- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>Untitled</title>
- <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.117/styles/kendo.common.min.css">
- <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.117/styles/kendo.rtl.min.css">
- <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.117/styles/kendo.default.min.css">
- <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.117/styles/kendo.mobile.all.min.css">
- <script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
- <script src="https://kendo.cdn.telerik.com/2018.1.117/js/angular.min.js"></script>
- <script src="https://kendo.cdn.telerik.com/2018.1.117/js/jszip.min.js"></script>
- <script src="https://kendo.cdn.telerik.com/2018.1.117/js/kendo.all.min.js"></script>
- <!--<script src="http://localhost:11207/JS/autocomplete.js"></script>-->
- <script src="https://autocompletefilter.azureedge.net/js-resource/autocomplete.js"></script> <!-- Azure CDN -->
- </head>
- <body>
- <input id="autocomplete" />
- <br />
- <br />
- <button id="btnClick" class="k-button">Click Me</button><label id="message"></label>
- <script>
- $("#btnClick").click(function () {
- var autoComplete = $("#autocomplete");
- var message = $("#message");
- if (autoComplete.length == 0) {
- message.text("Element Doesn't Exists in DOM").addClass("notExist")
- }
- else {
- message.text("Element Exists in DOM").addClass("exist")
- }
- });
- </script>
- <style>
- #message {
- margin-left:10px;
- }
- .exist{
- color:green
- }
- .notExist{
- color:red
- }
- </style>
- </body>
- </html>

Sagar Pandurang KapPosted Feb 25, 2018, 10:41 PM
Good article.Keep posting....