Search code examples
javascripthtmlcsscode-injectionsquarespace

How to add JavaScript code injection on squarespace to change href attribute?


I am trying to change the link on my squarespace website by inserting a code injection. I am adding the following code:

<script>
  var element = document.getElementsByClassName('eventitem-backlink')[0];
  element.setAttribute('href', '/archive/2017');
</script>

However, this does not work as element is undefined. The document.getElementsByClassName call returns a list of length one with the element I want to edit however when I try to extract it, it is undefined.

When I run the following code:

 console.log(document.getElementsByClassName('eventitem-backlink'));
 console.log(document.getElementsByClassName('eventitem-backlink')[0]);

it produces the following:

screenshot of console


Solution

  • You are calling the function too early in the process. Try:

    <script>
      (function() {
    
        function fn() {
          var element = document.getElementsByClassName('eventitem-backlink')[0];
    
          if (element) {
            console.log('element found');  
            element.setAttribute('href', '/archive/2017');
          } else {
            console.log('element not found yet');    
            setTimeout(fn, 200);
          }
        }
    
        fn();
      })();
    </script>