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.
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' ); } ?>
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 :)
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 usedocument.querySelector('.added_to_cart')
which will return the first found, or null. – Ian