我正在嘗試洗掉沒有 id 和 class 的 div<div>而不洗掉其子級。
<div class="struc">
..
..
<div class="required-field half-control form-group has-feedback">
<label for="fxb_d56c971 hljs-attr">control-label">First Name</label>
<input id="fxb_d56c971a hljs-attr">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 hljs-attr">control-label">First Name</label>
<input id="fxb_d56c971a hljs-attr">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>
任何建議或幫助將不勝感激。
提前致謝
uj5u.com熱心網友回復:
您的代碼是正確的,除了兩個錯誤:
$(findExtraDiv).idjQuery 沒有“id”屬性。應該$(findExtraDiv).attr('id') == undefined$(findExtraDiv).attr("class") == ""缺少的屬性回傳“未定義”,而不是空字串。你應該有$(findExtraDiv).attr("class") == undefined
通過這兩個修改并假設您的“$(el)”是正確的,您的代碼將起作用。
uj5u.com熱心網友回復:
下面的代碼可以找出所有沒有屬性的 div 元素,然后將其解包。這將回傳您請求的輸出。
const noAttributeElems = $("div").filter(function(){
if(this.attributes.length === 0){
$(this).contents().unwrap();
}
});
uj5u.com熱心網友回復:
請試試這個:
$(".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/h4smbqnu/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/495682.html
標籤:javascript jQuery 展开
上一篇:使用一元運算子“ ”。while回圈中的Lint錯誤
下一篇:反應按鈕不可點擊
