jquery怎么判断指定子元素是否存在

 3815

判断方法:1、使用“$("父元素").has("子元素").length”语句,如果返回值为1,则指定子元素存在;2、使用“$("父元素").children("子元素").length”语句,如果返回值大于等于1,则指定子元素存在。


jquery怎么判断指定子元素是否存在


jquery判断指定子元素是否存在

方法1:利用has() 方法

has() 将匹配元素集合缩减为拥有匹配指定选择器或 DOM 元素的后代的子集。

  1. <!DOCTYPE html>
  2. <html>
  3.     <head>
  4.         <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
  5.         <script type="text/javascript">
  6.             $(document).ready(function() {
  7.                 $("button").click(function() {
  8.                     if ($("div").has("span").length) {
  9.                         console.log("指定子元素存在")
  10.                     } else {
  11.                         console.log("指定子元素不存在")
  12.                     }
  13.                 });
  14.             });
  15.         </script>
  16.     </head>
  17.  
  18.     <body>
  19.         <div style="border: 1px solid red;">
  20.             <p>子元素1</p>
  21.             <span>子元素2</span>
  22.         </div><br>
  23.         <button>指定子元素span是否存在</button>
  24.     </body>
  25. </html>


jquery怎么判断指定子元素是否存在


方法2:使用children()

children() 方法返回返回被选元素的所有直接子元素。

  1. <!DOCTYPE html>
  2. <html>
  3.     <head>
  4.         <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
  5.         <script type="text/javascript">
  6.             $(document).ready(function() {
  7.                 $("button").click(function() {
  8.                     if ($("div").children("p").length) {
  9.                         console.log("指定子元素存在");
  10.                         console.log($("div").children("p").length);
  11.                     } else {
  12.                         console.log("指定子元素不存在");
  13.                         console.log($("div").children("p").length);
  14.                     }
  15.                 });
  16.             });
  17.         </script>
  18.     </head>
  19.  
  20.     <body>
  21.         <div style="border: 1px solid red;">
  22.             <p>子元素1</p>
  23.             <span>子元素2</span>
  24.             <span>子元素2</span>
  25.             <p>子元素3</p>
  26.             <p>子元素4</p>
  27.         </div><br>
  28.         <button>指定子元素是否存在</button>
  29.     </body>
  30. </html>


jquery怎么判断指定子元素是否存在

本文网址:https://www.zztuku.com/detail-11162.html
站长图库 - jquery怎么判断指定子元素是否存在
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐