jQuery length check if an element exists

Introduction

Use the jQuery .length property to determine whether an element exists or not.

View in separate window

<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Test Element Exists or Not</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        if($("#myDiv").length){
            document.getElementById("demo").innerHTML = "The element you're testing is present.";
        }/*from   w  w w.  j av  a 2 s .c  o m*/
    });
});
</script>
</head>
<body>
    <p id="demo"></p>
    <div id="myDiv"></div>
    <p>The quick brown fox jumps over the lazy dog</p>
    <button>Check Element</button>
</body>
</html>



PreviousNext

Related