移除没有class和id的div,但不移除它的子div



我试图删除没有id和类别<div>的div,而不删除其子div。

<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> 

我尝试了下面的代码,但不工作

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,但无法删除父div只有

这就是我想要的

<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>
如有任何建议或帮助,我将不胜感激。

Thanks in advance

请试试这个:

$(".struc div").each(function(){
let temp = $(this).html();
if($(this).attr('id')===undefined){
console.log('id is undefined');
$(this).remove();
$('.struc').append(temp);
}
})

下面是jsfiddle中的一个工作示例:

https://jsfiddle.net/vkcds1p0/

你的代码是正确的,除了两个错误:

  • $(findExtraDiv).idjQuery没有"id"财产。应该是$(findExtraDiv).attr('id') == undefined
  • $(findExtraDiv).attr("class") == ""missing属性返回'undefined',而不是空字符串。你应该有$(findExtraDiv).attr("class") == undefined

经过这两处修改,假设您的"$(el)"是正确的,你的代码将工作。

下面的代码可以找出所有没有属性的div元素,然后展开它。这将返回您所请求的输出。

const noAttributeElems = $("div").filter(function(){ 
if(this.attributes.length === 0){
$(this).contents().unwrap();
} 
});

最新更新