2
votes

I am trying to change the innerHTML of a "View cart" button with a dynamically generated div class on Wordpress/Woocommerce. I asked a previous question about this and was suggested (thank you Mike :) ) that because JS is an onload event, the class only changes after the user clicks an "add to cart" button so the js never runs in time.

I need to know how to change the innerHTML of the "view cart" button before anyone sees it. I would like to change the words "view cart"--->"view cats".

Here is my site: http://woocommerce-8778-19565-47619.cloudwaysapps.com/product-category/jewelry#. Please click "add to cart" and see "View cart" button appear.

I wrote some very basic JS:

   1. window.onload = function viewcart(){
   2.   document.querySelectorAll('.added_to_cart').innerHTML="view cats";
   3.  //  document.querySelector('a.added_to_cart.wc-forward:before').innerHTML="view cats";
   4. //  document.getElementsByClassName('.wc-forward::after').innerHTML="view cats";
   5. }

3-4 are examples of some ways I tried to solve the issue.

SOMETIMES the 'Cannot set property 'innerHTML' of null' message appears, but SOMETIMES it does not. Element Inspector shows the JS is loading though!

What I did in order (step 1, step 2, step 3): 1. Loaded the js to my Wordpress (using CHILD theme) by adding the external js sheet (viewcart.js) to the child theme file w/STFP.

  1. Added the following to CHILD theme's functions.php:

    <?php
    add_action( 'wp_enqueue_scripts', 'child_add_scripts' );
    function child_add_scripts() {
    wp_register_script(
    'viewcartscript',
    get_stylesheet_directory_uri() . '/viewcart.js',
    true,
    false
    );
    wp_enqueue_script( 'viewcartscript' );
    }
    ?> 
    
  2. Tried changing true to false and removing one of the "true"/"false" from the php function.

I will choose best answer more quickly than last question (2 days ago). Thank you in advance for ANY help. You guys are truly the best xo :)

1
document.querySelectorAll('.added_to_cart') will return an "array" of matching elements. You need to loop over that and set each .innerHTML. Or if you expect only one, just use document.querySelector('.added_to_cart') which will return the first found, or null.Ian
Hi Ian, Thank you so much for your reply :) Sorry I did not mention, but I already tried document.querySelector without 'All'. Unfortunately the first 'view cart' does not get edited by the js even then. So I dont know if loop will help.xkurohatox

1 Answers

0
votes

Document.querySelectorAll('button.added_to_cart') returns a list (nodelist) of the selectors in the document, that match '.added_to_cart'. As Ian said, the best way would be to loop this list and change their element's inner html one by one. CSS Pseudo-classes will never return any elements. Edited: You could also use var elements = document.getElementsByClassName('added_to_cart'); For ( var i=0; i < elements.length; i++) elements[i].innerHtml = 'view cats';