Selecting DOM elements with JavaScript in Shopify

Hi,

I’m trying to create a modal that will be triggered by JavaScript and am having some trouble getting things to work.

Here are the details:

  1. I’ve created a Snippet element that is rendered in the “theme.liquid” file

2a. I’ve add CSS to hide the Snippet element

2b. There is also CSS that can show that Snippet element. I want this to be added/toggled with JavaScript

.form-container-ja-outer-wrapper {
  display: none;
}

.form-container-ja-outer-wrapper.paragraph-class {
  display: block;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: #000000a6;
  z-index: 1045;
}
  1. I’ve created a section in Shopify that has a button element and some JavaScript that is intended to add the CSS class “.paragraph-class” to “.form-container-ja-outer-wrapper” in order to show the Snippet element.


  

  1. I’m getting this error message in the console.

Hoping someone can help me trouble shoot this DOM selection issue with JS and Shopify.

Here is the test page I’m working on:

https://liftow.com/pages/ja-sandbox

Thanks!

Make sure the javascript that targets element is AFTER the target elements in the HTML source order.

html/DOM doesn’t“hoist” html tags

Or use a document load event to wrap the logic for the element variables

Proper way to ask questions!

The problem is that when browser runs you JS code the entire document is not processed yet, so form can not be found.
testButton though is found because it is above your JS code. It is not Shopify-specific.

So i agree with Paul, your options are:

  1. Move your JS to be below both button and popup HTML;

  2. Use either document load or DOMContentLoaded event to run your JS code:

document.addEventListener( 'DOMContentLoaded', () => {
  const testBtn = document.querySelector('#modal-btn-test');
  const form = document.querySelector(".form-container-ja-outer-wrapper");

  if (!testBtn || !form) return;  // better check anyway

  testBtn.addEventListener('click', () => {
    form.classList.toggle("paragraph-class");
  });
});

Plus:

  1. Run your JS code from the .js file which is either defer’red or loaded at the bottom of your document.

3a. May try the {% javascript %} tag: https://shopify.dev/docs/storefronts/themes/architecture/sections/section-assets#javascript if you do not want to separate JS from HTML.

Awesome. Thanks @tim_1 ! That makes total sense.

Appreciate the assistance from yourself and @PaulNewton

Thanks for pointing me in the right direction @PaulNewton !

That makes total sense. Appreciate the reply!