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

Time:09-02

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 data-test="cart-item-product-title">BULK Powder 50 lbs.</h4>

Payment option: <li data-test="accordion-item_paypalcommerce">

CodePudding user response:

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  data-test="cart-item-product-title">BULK Powder 50 lbs.</h4>

Payment options:
<li  data-test="accordion-item_paypalcommerce">Cash</li>
<li  data-test="accordion-item_paypalcommerce">Credit</li>

  • Related