10Y01
10Y01

Reputation: 13

Delete DOM generated elements without <img> inside

A lot of .cell elements are added to the DOM on document load. Only some of them are needed. If an <img> was also created within them, they are needed. If an <img> element was not created within the .cell elements, then delete the whole .cell element. If the <img> was created then do nothing.

How can I do that?

<div class="cell">
    <div class="a-class">
        <div class="always-generated-div"></div>
        <img> <!-- if generated --->
    </div>
 </div>
jq(".cell img").each(function() {
    if (jq(this).length > 0) {
        console.log("Oh There You Are");
    } else { 
        console.log("Empty elements erased");
        jq( ".cell" ).remove();
    }
});

Upvotes: 1

Views: 50

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337590

You can select a parent by their child elements using the :has() selector (and the :not() selector in this case too). From there, you can remove() them. Try this:

$('.cell:not(:has(img))').remove();

Working example

Upvotes: 3

Satpal
Satpal

Reputation: 133403

You can use :empty selector

Select all elements that have no children (including text nodes).

jq(".cell:empty").remove()

Upvotes: 1

Related Questions