如何使用jQuery隐藏不包含特定文本(*)的子元素父元素
解决jQuery通过子元素ID筛选并隐藏不含特定文本的父元素问题
需求
- 通过子元素ID作为选择器,隐藏不包含特定文本(
*)的父元素,必须使用jQuery实现。
现有代码
HTML代码
<div> <label> First name <font color="red">*</font> <input type="text" id="guest_first_name"> </label> </div> </br> <div> <label> Last name <input type="text" id="guest_last_name"> </label> </div>
jQuery代码
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> <script> $(document).ready(function() { let checkthis = $("#guest_first_name, #guest_last_name").parent(); var removewithout = "*"; checkthis.not(removewithout).hide(); }) </script>
问题原因
原代码的错误点:
.not()方法无法直接接收文本字符串作为筛选条件,该方法仅支持选择器、DOM元素或jQuery对象作为参数。- 未正确提取父元素的文本内容进行目标符号的检测,导致无法判断元素是否符合隐藏条件。
修正后的代码
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> <script> $(document).ready(function() { // 选中目标子元素,遍历它们的直接父元素(label标签) $("#guest_first_name, #guest_last_name").parent().each(function() { // 获取父元素的纯文本内容,去除首尾空格后检查是否包含* if (!$(this).text().trim().includes('*')) { // 隐藏不包含*的父元素;若需隐藏外层div,改为$(this).parent().hide() $(this).hide(); } }); }); </script>
代码说明
- 用
$("#guest_first_name, #guest_last_name")定位目标子元素,通过.parent()获取它们的直接父元素(<label>)。 - 调用
.each()遍历每个父元素,逐个进行文本检测。 $(this).text().trim()提取父元素的所有文本内容并去除首尾空格,避免空格干扰判断逻辑。- 通过
includes('*')判断文本中是否包含目标符号,不包含则调用.hide()隐藏该元素。
内容的提问来源于stack exchange,提问作者WheresMyElement
相关产品推荐
相关产品推荐

