Q:

How to check if an element exists in jQuery

0

How to check if an element exists in jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the jQuery .length Property

You can use the jQuery .length property to determine whether an element exists or not in case if you want to fire some event only if a particular element exists in DOM.

Here's an example that displays an alert on button click if the specified element exists.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Test If an Element Exists</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        if($("#myDiv").length){
            alert("The element you're testing is present.");
        }
    });
});
</script>
</head>
<body>
    <div id="myDiv"></div>    
    <p>The quick brown fox jumps over the lazy dog</p>
    <button>Check Element</button>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to move an element to left, right, up and down... >>
<< How to stop firing event until an effect is finish...