jQuery如何移除无id无class的div标签且保留其内部子元素
问题需求
需要移除既无id属性也无class属性的裸<div>标签,且保留该div包裹的所有内部子元素不被删除。
原始DOM结构如下:
<div class="struc"> .. .. <div class="required-field half-control form-group has-feedback"> <label for="fxb_d56c971 class=" control-label">First Name</label> <input id="fxb_d56c971a class="design_textfield" type="text" value="" placeholder="First Name*"> <div> <span class="field-validation-error" data-valmsg-replace="true"> <span id="fxb_d56c971a" class="">First Name is required.</span> </span> </div> </div> .. .. </div>
原有代码失效原因
之前编写的jQuery代码无法生效,核心是两个判断逻辑存在错误:
- jQuery对象本身没有
.id属性,只有原生DOM节点才能直接读取.id,$(findExtraDiv).id永远返回undefined,判断条件直接失效 - 完全没有
class属性的元素,调用.attr("class")返回值是undefined,不是空字符串"",等于空串的判断永远不会命中
原有错误代码如下:
var findExtraDiv = $(el).prev('label').parent(); if ($(findExtraDiv).prop("tagName").toLowerCase() == 'div') { if (($(findExtraDiv).id == null) && ($(findExtraDiv).attr("class") == "")) { var cnt = $(findExtraDiv).contents(); $(findExtraDiv).replaceWith(cnt); } }
解决代码
批量处理方案
如果要一次性移除页面内所有符合规则的裸div,直接使用下面的代码即可:
// 匹配所有不带id、不带class属性的div标签 $('div:not([id]):not([class])').each(function() { // 用div内部的所有内容替换掉div本身,实现去壳留内容的效果 $(this).replaceWith($(this).contents()); });
针对当前定位逻辑的修复版
如果已经通过现有逻辑定位到了目标div,只需要修正判断条件即可:
var findExtraDiv = $(el).prev('label').parent(); if (findExtraDiv.is('div')) { // 取原生DOM节点判断id是否为空,同时判断class属性不存在 if (!findExtraDiv[0].id && !findExtraDiv.attr('class')) { findExtraDiv.replaceWith(findExtraDiv.contents()); } }
处理完成后的预期DOM结构:
<div class="struc"> ... <div class="required-field half-control form-group has-feedback"> <label for="fxb_d56c971 class=" control-label">First Name</label> <input id="fxb_d56c971a class=" design_textfield" type="text" value="" placeholder="First Name*"> <span class="field-validation-error" data-valmsg-replace="true"> <span id="fxb_d56c971a" class="">First Name is required.</span> </span> </div> ... </div>
注:
.contents()方法会获取元素内部的所有节点,包含普通元素、文本节点、注释节点,替换后不会丢失任何内部内容。
内容的提问来源于stack exchange,提问作者Owais Ahmed
相关产品推荐
相关产品推荐

