如何通过子元素ID为父级div添加类(jQuery实现)
实现方法
没问题,通过jQuery可以轻松搞定这个需求,这里有两种实用的实现方式:
方法1:使用closest()(推荐,适配性更强)
这个方法会从目标textarea元素向上遍历DOM树,找到最近的匹配指定选择器的父容器,就算后续DOM结构有小调整也不容易出错:
// 通过textarea的ID定位元素,向上查找最近的.ugc-input-wrapper容器,添加新类 $('#attachment_caption').closest('.ugc-input-wrapper').addClass('classname');
方法2:使用parent()(仅适用于textarea是目标div的直接子元素时)
如果你能确定<textarea>就是<div class="ugc-input-wrapper">的直接子元素,也可以用更简洁的parent()方法:
$('#attachment_caption').parent().addClass('classname');
额外提示
- 要是需要一次性添加多个类,直接在
addClass()里用空格分隔类名就行:addClass('classname second-class') - 你的原始HTML结构参考:
<div class="ugc-input-wrapper"> <label for="attachment_caption">Caption</label> <textarea name="post_content" id="attachment_caption"></textarea> </div>
执行代码后,目标div会变成:
<div class="ugc-input-wrapper classname"> <label for="attachment_caption">Caption</label> <textarea name="post_content" id="attachment_caption"></textarea> </div>
内容的提问来源于stack exchange,提问作者Muhammad Rizwan
相关产品推荐
相关产品推荐

