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

JavaScript检测p元素类名异常:始终提示“No”求解决

Why Your Class Check Always Returns "No"

Hey there, let's break down why your code keeps showing "No" instead of "Yes" even though the <p> element has the red_cross class.

The Core Issue

Your current code is comparing a DOM element object directly to a string, which will never match:

if (check_ll_ctq == "red_cross") { ... }

document.getElementById("ll_ctq") returns the actual <p> element node, not its class name. Comparing this object to the string "red_cross" will always evaluate to false.

Fixing the Code

To properly check if an element has a specific class, use the classList.contains() method (supported in all modern browsers). Here's the corrected version:

Corrected JavaScript Function

function ll_ctq() {
  // Get the element
  const check_ll_ctq = document.getElementById("ll_ctq");
  
  // First make sure the element exists to avoid errors
  if (!check_ll_ctq) {
    alert("Element not found!");
    return;
  }
  
  // Check if the element has the target class
  const targetClass = 'red_cross';
  if (check_ll_ctq.classList.contains(targetClass)) {
    alert("Yes");
  } else {
    alert("No");
  }
}

Full HTML with Corrected Code

<body onload="ll_ctq()">
  <p id="ll_ctq" class="red_cross">Hello</p>
</body>

What Changed?

  • We first verify that the element exists (prevents runtime errors if the ID is mistyped)
  • We use classList.contains(targetClass) to properly check for the presence of the class, which returns a boolean (true if the class exists, false otherwise)

This will now correctly alert "Yes" when the <p> element has the red_cross class, and "No" if it doesn't.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:06:08