How to properly insert java script into Shopify theme

SureBuy
Excursionist
47 2 11

I'm facing an issue with dynamically updating the heading on my product page based on a UTM parameter in the URL. I've implemented the following JavaScript code, but it's causing the heading to be duplicated:

I think I'm not connecting the script well with how shopify themes are structured can someone help me real quick? I simply want to add the keyword (test) To the end of my product's titles, but now it comes up as duplicated and there is a bit of padding, so its not implementing correctly. Can someone take a look at it RQ?:

Capture.PNG

 

<script>
document.addEventListener('DOMContentLoaded', function() {
  // Function to get UTM parameter from URL
  function getUTMParameter(name) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
  }

  // Get the 'utm_content' parameter from the URL
  const keyword = getUTMParameter('utm_content');

  // Check if the keyword is present and update the product title
  if (keyword) {
    const titleElement = document.querySelector('.product__title'); // Adjust the selector accordingly
    if (titleElement) {
      const originalTitle = titleElement.textContent;

      // Check if the title hasn't been modified already
      if (!originalTitle.includes(keyword)) {
        // Create a new h1 element, update its content, and replace the existing title element
        const newTitleElement = document.createElement('h1');
        newTitleElement.textContent = originalTitle + ' - ' + keyword;
        titleElement.parentNode.replaceChild(newTitleElement, titleElement);
      }
    }
  }
});
</script>

 

Reply 1 (1)

kevinkarma55
Excursionist
30 1 6

Hey, 
Why don't you add the extra keyword or string to the existing heading without creating a new one? 

titleElement.insertAdjacentHTML( 'beforeend', keyword);

 -the padding might be caused by creating a new element (h1)

Skilled in building custom Shopify theme