You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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>

问题原因

原代码的错误点:

  1. .not()方法无法直接接收文本字符串作为筛选条件,该方法仅支持选择器、DOM元素或jQuery对象作为参数。
  2. 未正确提取父元素的文本内容进行目标符号的检测,导致无法判断元素是否符合隐藏条件。

修正后的代码

<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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 02:45:16