<!DOCTYPE html> <html> <head> <title>判断元素是否存在子元素</title> <script src=https://www.php.cn/faq/"https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <div id="container"> <p>这是一个包含子元素的容器</p> </div> <div id="empty-container"> <!-- 这是一个空的容器 --> </div> <script> // 判断container元素是否包含子元素 if($('#container').children().length > 0) { console.log('container元素包含子元素'); } else { console.log('container元素不包含子元素'); } // 判断empty-container元素是否包含子元素 if($('#empty-container').children().length > 0) { jQuery实现判断元素是否存在子元素功能 console.log('empty-container元素包含子元素'); } else { console.log('empty-container元素不包含子元素'); } </script> </body> </html>
登录后复制