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

如何在点击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 #container that includes an id attribute. You can use either span[id]:first to directly select the first matching span, or chain .first() to narrow down the results.
  • Apply the class: Use jQuery's .addClass() method to attach the hero class 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:36:24