Pedro Mendes
Pedro Mendes

Reputation: 99

jquery remove div inside of other divs

I have a main <div> with many other divs inside like this:

[HTML]

<div class="container">
  <div class="row">
    <div class="col">
      <div class ="deleteMe">
       delete me 
    </div>
    </div>
  </div>  
</div>

I want to remove the div with class name "deleteMe", i tried to remove it by using ,find() method from jquery:

$('.container').find('.row').find('.col').find('deleteMe').remove();

or

$('.container').find('.row').find('.col').removeClass('.deleteMe');

But didn't work, what is the best way to remove it?

here is the fiddle link test this exemple:

fiddle

//$('.container').find('.row').find('.col').find('deleteMe').remove();

$('.container').find('.row').find('.col').removeClass('.deleteMe');
.row {
  background: #f8f9fa;
  margin-top: 20px;
}

.col {
  border: solid 1px #6c757d;
  padding: 10px;
}

.deleteMe {
  border: solid 1px #6c757d;
  padding: 10px;
  background: red;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- 
  Bootstrap docs: https://getbootstrap.com/docs
-->

<div class="container">
  <div class="row">
    <div class="col">
      <div class="deleteMe">
        delete me
      </div>
    </div>
  </div>
</div>

Upvotes: 0

Views: 1312

Answers (4)

as-if-i-code
as-if-i-code

Reputation: 2340

below line will do

$( ".container .row .col .deleteMe" ).remove(); 

Upvotes: 1

collapsar
collapsar

Reputation: 17238

You do not need jquery for the job, see the following code snippet ( The setTimeout wrapper delays the deletion by 1s and only serves to see what is happening.

setTimeout ( () => {
    document.querySelector(".deleteMe").remove();
}, 1000);
<div class="container">
  <div class="row">
    <div class="col">
      <div class ="deleteMe">
       delete me 
    </div>
    </div>
  </div>  
</div>

Given your original code, you might want the selector to be more specific:

 document.querySelector(".container > .row > .col > .deleteMe").remove(); // Adjacent sub-selectors reference elements in a parent/child relation      
 document.querySelector(".container .row .col .deleteMe").remove(); // The elements are in a ancestor/descendant relation, not necessarily child/parent

Upvotes: 2

Vishal Pawar
Vishal Pawar

Reputation: 376

Try this

 $(".container .deleteMe").remove();

Upvotes: 2

Zoldszemesostoros
Zoldszemesostoros

Reputation: 397

There is a little typo in your code: a . is missing before deleteMe.

$('.container').find('.row').find('.col').find('.deleteMe').remove();

correctly.
Another thing: removeClass don't remove an element with the specified class; It removes the specified class from the element.

Upvotes: 0

Related Questions