Hi @HashimovH
Great question — working with different Shopify themes can definitely be a challenge due to variations in markup and class naming conventions.
Here are a few best practices that might help you optimize your approach:
1. Use data-* Attributes When Possible
Shopify themes often include data-product-id, data-product-title, or similar attributes in product grid elements. These are much more reliable for targeting elements than CSS class names, which can vary from theme to theme.
document.querySelectorAll('[data-product-id]').forEach((productEl) => {
// Append your custom button here
});
2. Defer Until DOM Is Ready
Always ensure your script runs after the DOM is fully loaded (especially important if you’re working with sections or apps that lazy-load content):
document.addEventListener("DOMContentLoaded", function () {
// your code
});
3. Theme-Agnostic Design
Avoid targeting classes like .product-card or .grid__item unless you’re building for a specific theme. Instead, write logic that detects structural patterns (like child elements inside a container with a known role or data-* attribute).
4. Use Mutation Observers
If you’re injecting content into dynamic areas (e.g., quick view modals, filters that re-render grids), MutationObserver can help:
const observer = new MutationObserver(() => {
// re-apply your changes after DOM updates
});
observer.observe(document.body, { childList: true, subtree: true });
5. Fallback Logic
If you’re building an app to be used across multiple themes, consider maintaining a small compatibility layer for the most popular themes where your selectors differ slightly.
Hope this helps! Keep building — the Shopify ecosystem definitely benefits from innovative developers like you.
Let me know if you have any issues with this!