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

判断指定元素父级div类名是否含collapsed-box的JS实现问题

Check if Closest .box Element Has 'collapsed-box' Class

Problem Statement

I have a collapsible box HTML generated by R Shiny:

<div class="box box-info collapsed-box">
  <div class="box-header">
    <h3 class="box-title">
      <div style="display: block; width: 74%; ">1. Governance framework</div>
    </h3>
    <div class="box-tools pull-right">
      <button class="btn btn-box-tool" data-widget="collapse">
        <i class="fa fa-minus"></i>
      </button>
    </div>
  </div>
  <div class="box-body" id="idtolocate" style="display: block;">
  </div>
</div>

I need to write JavaScript that finds the nearest div with the .box class starting from the element with id idtolocate, then returns true if that div has the collapsed-box class. The code I tried isn't working:

function isCollapsed() { 
  alert($('#idtolocate').closest('.box').classList.contains('collapsed-box')) 
}

What's Wrong with Your Code?

The issue here is that you're mixing jQuery objects and native DOM API. $('#idtolocate').closest('.box') returns a jQuery-wrapped object, but classList is a property of native DOM elements—jQuery objects don't have this property. That's why your code throws an error or returns undefined.

Fixes & Solutions

Option 1: Use jQuery's hasClass() Method (Recommended)

jQuery has a built-in method specifically for checking if an element has a class, which is clean and idiomatic:

function isCollapsed() {
  const collapsedStatus = $('#idtolocate').closest('.box').hasClass('collapsed-box');
  alert(collapsedStatus);
  return collapsedStatus;
}

Option 2: Convert jQuery Object to Native DOM Element

If you prefer using the native classList API, you can convert the jQuery object to a native element using either [0] or .get(0):

function isCollapsed() {
  // Get the native DOM element from the jQuery object
  const boxElement = $('#idtolocate').closest('.box')[0]; 
  // Alternatively: $('#idtolocate').closest('.box').get(0)
  
  const collapsedStatus = boxElement.classList.contains('collapsed-box');
  alert(collapsedStatus);
  return collapsedStatus;
}

Bonus: Ensure DOM is Loaded

Make sure your code runs after the DOM is fully loaded, otherwise the idtolocate element might not exist yet. Wrap it in jQuery's document.ready():

$(document).ready(function() {
  function isCollapsed() {
    return $('#idtolocate').closest('.box').hasClass('collapsed-box');
  }

  // Example usage
  // console.log(isCollapsed());
});

内容的提问来源于stack exchange,提问作者Mario

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 06:22:37