I’m building a website where I want to run a secondary function when the “Add to Cart” button is clicked.
For some reason when I try using any sort of event listener or getElementsbyTagName to access the button created by the BuyButton script, it always returns as undefined and gives me this error:
Uncaught TypeError: Cannot set properties of undefined (setting ‘innerHTML’)
Here’s my code:
<script src="http://sdks.shopifycdn.com/buy-button/1.0.0/buybutton.js" ></script>
</head>
<body>
<div id="shopifyDiv"></div>
<script type="text/javascript">
/*<![CDATA[*/
var client = ShopifyBuy.buildClient({
domain: 'shopify.myshopify.com',
storefrontAccessToken: '(myTokenHere)',
});
var ui = ShopifyBuy.UI.init(client);
ui.createComponent('product', {
id: (myIdHere),
node: document.getElementById('shopifyDiv'),
options: {
product:{
width: '350px',
contents:{
img: false,
button: true,
title: false
},
text: {
button: 'Add to cart'
},
},
cart:{
startOpen: false
},
}
});
/*]]>*/
</script>
<script type="module">
document.getElementsByTagName('button')[0].innerHTML = 'hello world';
</script>
</body>
</html>
I removed the Shopify specific accessToken & domain name for security purposes.
Any help in understanding why these DOM Elements that are being created by the Shopify script are inaccessible would be highly appreciated.