How can I remove an element with no attributes and a child element?

I have a list of elements and I want to remove div elements with no attributes and a child element.

Sample code:

<div class="wrapper">
  <div class="xx-1"></div>
  <div id="yy-1"></div>
  <div></div>
  <div><h1>Hello World!</h1></div>
  <div></div>
  <div></div>
</div>

      

How can I remove <div></div>

inside a wrapper class?

+3


source to share


3 answers


If the conditions for deletion are:

  • DIV tags
  • which have no attributes
  • and have no children

Then you probably need a filter:



$(".wrapper div").filter(function() {
    return this.attributes.length == 0
        && this.childNodes.length == 0;
}).remove();

      

A selector div:empty

in jQuery will remove all DIV tags without child nodes, including DIV tags that have attributes and child nodes.

+3


source


you can use a filter.

$(".wapper div").filter(function () {
    return $(this).text() == "";
}).remove();

      



This will remove all empty divs.

+1


source


after some research and trying, I ended up with this:

$('div:not([class]):not([id]):not(:has(*))').remove();

      

JSFiddle Demo

edit: ok, this is not a solution yet as it just checks the attributes class

and id

.

0


source







All Articles