Site logo

Archived topic

Trouble inserting custom javascript into generatepress website

5 replies · Started by Benjamin on October 7, 2021

Viewing posts 1–6 of 6

Hi Team,

I have created a website where I want custom javascript to be applied to the front page.

So I followed David's instruction here to create a hook and insert JS code in to wp_head.

However when I navigate to my website The javascript code appears not in <head></head> but in the body. Please advise on how to get this custom JS code to be in <head> as the hook suppose to do.

Hi there,

you need to wrap your Javascript in <script> tags:

<script>
Your Javascript here
</script>

When I put the js code between the tag <script></script> the code will appear in the header when I inspect in the browser. However I couldn't reference html element from JS. So I made a simple html and JS just to test:


    <div>
        <input type="text" id="lname" name="lname">
    </div>

For JS code I insert into the hook element
Hook: wp_head
Location: Front Page


<script>
	document.getElementById("lname").value = "My Value";
</script>

However when I publish the page and look it up in the browser the input tag wasn't populated with "My Value". When I inspect the code via browser there is an error:

Uncaught TypeError: Cannot set properties of null (setting 'value')

May I know how can I reference html element like input tags from JS?

For that kind of use - you will require the script to fired after the HTML has been rendered.
So change the Hook from wp_head to wp_footer

It works thanks David!

Glad to hear that!

This archived topic is closed to new replies.