skip to Main Content

I tried following the information here, editing it to match my needs, but so far it’s not working.
I’m trying to hide a parent div with two child elements. The parent div is part of a list, all with the same classes, and each div has two child elements: an input, and an image. Each input has a unique "data-wapf-label" that I’m trying to select so that I can hide the parent div. The HTML is as follows:

<div class="has-pricing wapf-swatch wapf-swatch--image">
  <input type="radio" id="wapf-field-61b148f2fc8fe_lzhx7" name="wapf[field_61b148f2fc8fe]" class="wapf-input" data-field-id="61b148f2fc8fe" value="lzhx7" data-wapf-label="Peppermint Mocha" data-is-required data-wapf-pricetype-"fx">
  <img src="...">
</div>

There are several pages where this product shows up, and rather than going in and deleting the product field (because I’ll just have to add it again next season), I’m trying to create a piece of code that will hide all the divs for all the products that have the above code (since each has a unique "id", I’d have to do it several times for each id using "selectElementById", and I’d like to avoid doing that, obviously).

I installed Code Snippets, but I’m having a bit of trouble with the Javascript. I should add that Code Snippets inserts code to the website via php (so php tags are required with every snippet). I’ve tried several things, but this is my latest version. It throws a syntax error "unexpected ‘hideFlavors’ (T_STRING), expecting ‘(‘".
Here’s my php/Javascript code:

<?php
add_action( 'wp_head', function hideFlavors() { ?>
<script>
    if var peppermintMocha = document.querySelectorAll("[data-wapf-label='Peppermint Mocha']") {
    peppermintMocha.parentNode.style.display = "none"; 
    }
</script>
<?php } );

I’ve also tried it with "document.querySelector" (without the "All"), but with the same or similar problem. When I do get the code to actually go through without any errors, it still doesn’t fix the problem.
At this point, I feel a little like the guy looking through the tank’s periscope on "Independence Day". No matter what I do, "target remains".

2

Answers


  1. <?php
    add_action( 'wp_head', function() {
        ?>
            <script>
                window.onload = function() {
                    document.querySelectorAll("[data-wapf-label='Peppermint Mocha']").forEach(function(el) {
                        el.parentNode.style.display = "none"; 
                    });
                };
            </script>
        <?php
    });
    ?>
    

    querySelectorAll returns an array of elements, so you need to loop through each element and hide their parent respectively.

    Login or Signup to reply.
  2. Instead querySelectorAll use querySelector. Then it would be work. But make sure that exists only one input field with the selector [data-wapf-label='Peppermint Mocha'].

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search