John John - 1 month ago 6
Javascript Question

Removing sibling div when another span element contains specific text

I am trying to remove div with

class=".basket__item-cell.basket__item-qty"
only when
hidden-sku
is equal to "020-01119".

I've tried different approaches using .each(function) or .next() but could not get my head around it. In order to illustrate the example I've added the code bellow.

Please note that I can not add any id's or classes and the order of the rows may vary.



(function($) {
$('.hidden-sku').filter(function() {
return $(this).text().indexOf("020-01119") !== false;
}).closest(".basket__item-cell.basket__item-name").next(".basket__item-cell.basket__item-qty").remove();
})(jQuery)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="basket__item-data basket__item-data--right">
<div class="basket__item-cell basket__item-name">
<h2 class="product-name">One </h2>
<span class="hidden-sku">020-01119</span>
</div>
<div class="basket__item-cell basket__item-price">
<span class="cart-price"><span class="price"><span class="currency"></span>18</span>
</span>
</div>
<div class="basket__item-cell basket__item-qty">
<div class="input-combobox main-input-combobox input-combobox__with-qty" data-label="Qty" data-range-min="1" data-range-max="12">1
</div>
</div>
</div>

<div class="basket__item-data basket__item-data--right">
<div class="basket__item-cell basket__item-name">
<h2 class="product-name">Two </h2>
<span class="hidden-sku">020-01117</span>
</div>
<div class="basket__item-cell basket__item-price">
<span class="cart-price"><span class="price"><span class="currency"></span>18</span>
</span>
</div>
<div class="basket__item-cell basket__item-qty">
<div class="input-combobox main-input-combobox input-combobox__with-qty" data-label="Qty" data-range-min="1" data-range-max="12">2
</div>
</div>
</div>

<div class="basket__item-data basket__item-data--right">
<div class="basket__item-cell basket__item-name">
<h2 class="product-name">Three </h2>
<span class="hidden-sku">020-01118</span>
</div>
<div class="basket__item-cell basket__item-price">
<span class="cart-price"><span class="price"><span class="currency"></span>18</span>
</span>
</div>
<div class="basket__item-cell basket__item-qty">
<div class="input-combobox main-input-combobox input-combobox__with-qty" data-label="Qty" data-range-min="1" data-range-max="12">3
</div>
</div>
</div>




Answer

This will do the job and arguably it's easier to understand what it's doing at glance.

I am also assuming the SKU is always going to be 020-01119 and never just containing that string? If that's not the case just put the indexOf back into the if condition.

(function($) {
  $('.basket__item-data').each(function () {
    var sku = $('.hidden-sku', this);

    if (sku.text() === '020-01119') {
      $('.basket__item-cell.basket__item-qty', this).remove();
    }
  });
})(jQuery);
Comments