Home >Daily Programming >HTML Knowledge >How to determine if an element exists with JQuery

How to determine if an element exists with JQuery

藏色散人
藏色散人Original
2018-12-13 16:15:4515118browse

JQuery determines whether an element exists. We can use the jQuery .length property to achieve this. When an event is triggered when a specific element exists in the DOM, you can use the jQuery .length property to determine whether the element exists.

How to determine if an element exists with JQuery

Below we will combine a simple code example to introduce to you the specific method of JQuery to determine whether an element exists.

The code example is as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JQuery判断元素是否存在的示例</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
       $(function () {
           $("button").click(function () {
               if($("#myDiv").length) {
                   alert("元素已存在");
               }
                   else {
                       alert("元素不存在");
                   }

           });
       });
    </script>
</head>
<body>
</body>
<div id="myDiv"></div>
<p>点击下面的按钮检查元素</p>
<button>检查元素</button>
</html>

In the above code, we added a click event to the button. When the button button is clicked, the method of judging the element will be triggered. If the specified div exists, it will A prompt of "Element already exists" pops up, otherwise a prompt of "Element does not exist" pops up.

The judgment result is as follows:

When there is a div, click the button to display the following picture:

How to determine if an element exists with JQuery

How to determine if an element exists with JQuery

When the div does not exist, click the button to display the following image:

How to determine if an element exists with JQuery

Note: The length attribute contains the number of elements in the jQuery object.

This article is an introduction to JQuery to determine whether an element exists. It is also very simple. I hope it will be helpful to friends in need!

The above is the detailed content of How to determine if an element exists with JQuery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn