Hide list item using data attribute when specific text is present on the page with JS

127 Views Asked by At

This is trying to hide a checkout payment option from appearing when specific items are in cart (shown on the same page). If the text "BULK" appears in the cart/page to hide a list option based on its data attribute? I've tried learning js and the last 2 hours of watching a course, I understand more but this still seems more advanced than what I can do right now. Would a boolean argument using string.search and insert div.style.display "none"?

Cart example to search for text:
<h4 class="product-title optimizedCheckout-contentPrimary" data-test="cart-item-product-title">BULK Powder 50 lbs.</h4>

Payment option: <li class="form-checklist-item optimizedCheckout-form-checklist-item" data-test="accordion-item_paypalcommerce">

1

There are 1 best solutions below

5
IT goldman On

Once you have a reference to the item (or items - same idea only in a loop) - read the text of the element. Using indexOf sounds reasonable to find a string inside another. And if all is well then just set display:none to the right payment option.

The javascript is basic, but you should also learn some about css selectors should you want to "select" the target elements using a different strategy.

var elem = document.querySelector(".product-title");
var bool = elem.innerText.indexOf('BULK')>=0
if (bool) {
  var li = document.querySelector("li[data-test='accordion-item_paypalcommerce']");
  li.style.display = 'none'
}
<h4 class="product-title optimizedCheckout-contentPrimary" data-test="cart-item-product-title">BULK Powder 50 lbs.</h4>

Payment options:
<li class="form-checklist-item optimizedCheckout-form-checklist-item" data-test="accordion-item_paypalcommerce">Cash</li>
<li class="form-checklist-item" data-test="accordion-item_paypalcommerce">Credit</li>