skip to Main Content

I need a little bit of help with my shopify store. I’m trying to change the class of a button in order to style it from the default class “btn” to “askAQButton”. However, the code for the buttons are not in the markup at all and so I can only assume they’re generated by JS by the shopify plugin itself.

I figured it should be simple and I should be able to just target the element by “id” with jquery and change class. However, the button doesn’t have an ID and neither does the href…

My next thought was okay, target the parent div by id, then target the class of the button and href and change it that way (to avoid targeting duplicate classes).

I just can’t seem to get it working.

Here is all the markup I’m given to implement this onto my store page:

enter image description here

Obviously a lot of it is irrelevant (probably all of it besides the parent div) however, when I load my page up after implementing this code it auto-generates this right under the second input:

<div class="wk-ask-order">
  <button class="wk-ask-a-question-order btn" style="display: inline-block;">Raise a Query
  </button>
  <a href="/pages/ask-a-question/orders" target="_blank" class="view-customer-queries btn">View Your Queries</a>
</div>

Can anyone help me with targeting it and changing the class names please.

2

Answers


  1. I’m not sure if I get the question right, but there might be a problem with the button having not yet been injected into the DOM at the time when your script is targeting it.
    Try waiting for the DOMContentLoaded event before executing your code:

    document.addEventListener('DOMContentLoaded', () => {
        const askAQBtn = document.querySelectorAll('.wk-ask-a-question-order')[0]; //there's probably a better selector
        askAQBtn.classList.replace('btn', 'askAQButton');
    });
    
    

    If that doesn’t work, have a look at MutationObserver to wait for the specific element to exist. I found a snippet for this on Github:

    https://gist.github.com/jwilson8767/db379026efcbd932f64382db4b02853e

    Login or Signup to reply.
  2. This was my answer it’s a bit lo-fi but I hope it gives you something to work from. I followed your idea regarding the parent div id.

    let parent = document.getElementById('wk-askme');
    let child_nodes = parent.childNodes;
    
    for (let i = 0; i < child_nodes.length; i++) {
      let item = child_nodes[i];
        if ($(item).attr('class') == "wk-ask-a-question-order btn") {
            $(item).attr('class', 'wk-ask-a-question-order askAQButton');
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search