Home > Blockchain >  Removing div with no class and id without removing its children
Removing div with no class and id without removing its children

Time:06-28

I am trying to remove div with no id and class <div> without removing its children.

<div >
..
..
<div >
  <label for="fxb_d56c971 >First Name</label>
  <input id="fxb_d56c971a  type="text" value="" placeholder="First Name*">
  <div>
    <span  data-valmsg-replace="true">
      <span id="fxb_d56c971a" >First Name is required.</span>
    </span>
  </div>
</div>
..
..
</div> 

I tried the following code which is not working

        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);
            }
        }

I can find the correct div but unable to remove the parent div only

This is what I want

<div >
...    
  <div >
    <label for="fxb_d56c971 >First Name</label>
    <input id="fxb_d56c971a  type="text" value="" placeholder="First Name*">
    <span  data-valmsg-replace="true">
      <span id="fxb_d56c971a" >First Name is required.</span>
    </span>
  </div>
...
</div>

Any suggestions or help would be appreciated.

Thanks in advance

CodePudding user response:

Try this, please:

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

Here goes a working example at jsfiddle:

https://jsfiddle.net/vkcds1p0/

CodePudding user response:

You code is correct except for two mistakes:

  • $(findExtraDiv).id jQuery has no "id" property. Should be $(findExtraDiv).attr('id') == undefined
  • $(findExtraDiv).attr("class") == "" missing attribute returns 'undefined', not empty string. You should have $(findExtraDiv).attr("class") == undefined

With these two modifications and assuming your "$(el)" is correct, your code will work.

CodePudding user response:

Below code can find out all div elements having no attributes and then unwrap it. This will return your requested output.

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