Home > Web Front-end > JS Tutorial > body text

How to detect if an element exists with jQuery

黄舟
Release: 2016-12-15 14:53:36
Original
1253 people have browsed it

How jQuery detects whether an element exists:
There may be situations in the code where different operations are performed based on whether the element exists, so it is necessary to determine whether the specified element exists.
Use $(selector) to get the set of matching elements, and the length attribute of the set of matching elements can get the number of matching elements in the set, so as long as you determine whether the length attribute value is zero, you can determine whether the element exists. The code example is as follows:

<!DOCTYPE html><html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.softwhy.com/" /> 
<title>蚂蚁部落</title>
<script src=" 
<script type="text/javascript">$(document).ready(function () {
  $("#check").click(function () {    if ($(".mytest").length > 0) {
      alert("此元素存在");
    }
  })
})</script><body><ul>
  <li>太阳出来了</li>
  <li>蚂蚁部落</li> 
  <li class="mytest">p+CSS教程</li>  </ul><button id="check">点击检测</button></body></html>
Copy after login

If the number of elements in the collection is greater than zero, then the element exists, otherwise the specified element does not exist.

The above is how jQuery detects whether an element exists. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!