如何在点击jQuery的container元素时为首个带id的子span添加hero类
Solution: Add Class to First Span with ID on Container Click
Got it, let's work through this problem together. Your goal is to add the hero class to the first <span> element inside #container that has an id attribute when the container is clicked—here's how to make that happen:
Key Steps to Implement
- Target the correct element: Use a jQuery selector to find the first
<span>inside#containerthat includes anidattribute. You can use eitherspan[id]:firstto directly select the first matching span, or chain.first()to narrow down the results. - Apply the class: Use jQuery's
.addClass()method to attach theheroclass to the selected element.
Complete Working Code
Here's the full, tested implementation:
HTML Structure
<div id="container"> <span id="hp"> add class here</span> <span id="hp"> Do not add class here</span> </div>
jQuery Event Handler
$("#container").on("click", function() { // Target the first span with an id attribute and add the hero class $(this).find("span[id]:first").addClass("hero"); });
Important Note
A quick best practice reminder: Having multiple elements with the same id (like hp here) is invalid HTML—IDs should be unique across your entire document. The code above will still work for your specific use case, but fixing the duplicate IDs will help avoid unexpected behavior in other parts of your project.
内容的提问来源于stack exchange,提问作者William Gao
相关产品推荐
相关产品推荐

