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 (trueif the class exists,falseotherwise)
This will now correctly alert "Yes" when the <p> element has the red_cross class, and "No" if it doesn't.
内容的提问来源于stack exchange,提问作者Raja
相关产品推荐
相关产品推荐

