Riots
Riots

Reputation: 67

Remove first element within every li

I want to remove the first element within every li element but my code only removes the a element from the first li and not all li

example below.

I have this

<ul class="myclass">
 <li class="product-category product">
  <a href="#"></a> <---Remove this element
  <a href="">
   all product info here
  </a>
 </li>
 <li class="product-category product">
  <a href="#"></a> <---Remove this element
  <a href="">
   all product info here
  </a>
 </li>
 <li class="product-category product">
  <a href="#"></a> <---Remove this element
  <a href="">
   all product info here
  </a>
 </li>
</ul>

jQuery("li.product-category>a").first().remove();

Upvotes: 0

Views: 50

Answers (3)

Dima Vak
Dima Vak

Reputation: 619

You can use something like that

let list = document.querySelectorAll('.product')
for (let item of list){
item.children[0].remove()
}
<ul class="myclass">
 <li class="product-category product">
  <a href="#">del</a>
  <a href="">
   all product info here
  </a>
 </li>
 <li class="product-category product">
  <a href="#">del</a>
  <a href="">
   all product info here
  </a>
 </li>
 <li class="product-category product">
  <a href="#">del</a> 
  <a href="">
   all product info here
  </a>
 </li>
</ul>

Upvotes: 0

matthias_h
matthias_h

Reputation: 11416

You could do it like this using each():

$("li.product-category").each(function() {
  $(this).find("a").first().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="myclass">
 <li class="product-category product">
 <a href="#"></a>
  <a href="">
   all product info here
  </a>
 </li>
 <li class="product-category product">
  <a href="#"></a>
  <a href="">
   all product info here
  </a>
 </li>
 <li class="product-category product">
  <a href="#"></a> 
   <a href="">all product info here
  </a>
 </li>
</ul>

Upvotes: 1

imvain2
imvain2

Reputation: 15847

A loop will make it work.

jQuery("li.product-category").each(function(){
    $(this).find("a").first().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="myclass">
 <li class="product-category product">
  <a href="#">aac</a> <---Remove this element
  <a href="">
   all product info here
  </a>
 </li>
 <li class="product-category product">
  <a href="#">aad</a> <---Remove this element
  <a href="">
   all product info here
  </a>
 </li>
 <li class="product-category product">
  <a href="#">eaa</a> <---Remove this element
  <a href="">
   all product info here
  </a>
 </li>
</ul>

Upvotes: 0

Related Questions