Setting h1 text with getElementById

Hi!

Ultimately I’m trying to set my H1 text to the name of the current page, using this script in an HTML embed element or in the Project Settings custom code section:

document.getElementById(“pagename”).textContent = location.pathname.split(“/”).slice(-1); //haven’t tried this part yet

But firstly I can’t get this to work using an HTML Embed element:

  document.querySelector("pagename").innerText = "Hello world";

or

  document.getElementById("pagename").textContent = "Hello world";

I’m setting my H1 element’s ID to pagename in the settings.
Any ideas would be greatly appreciated. Thanks!

K

1 Like

Hi K,

Always share your read-only project link. If we can’t see your project, very little we can do to help.

That said, my first guess would be is that in the designer you’ve set your ID with different casing like PageName or Pagename. ID’s are case-sensitive, so they need to match exactly what you’re referencing in your script.

Thanks, I double checked and seems the caps are okay.

https://preview.webflow.com/preview/wakedesigns?utm_medium=preview_link&utm_source=designer&utm_content=wakedesigns&preview=0eb365d975fbc51d7cad9114dde9a201&pageId=639d1feabcb19160e2cf5862&workflow=preview

What’s the pwd on your webflow.io site? You can PM it to me if you need to.
Checking for script errors in the console.

True I should have done that. Thanks for helping. Should the text load in the designer or do i need to publish and view live? It seems it would as I’ve linked images before in the embed element and it loaded in the designer.

I think this is it- you have the script running before the element exists.
In an inline script like this, it can only access DOM elements that have already been created.

image

You should be able to fix it by editing your nav symbol and then move the HTML Embed to the bottom of your nav, after #newpagename

Great, thank you, that worked. I see the error in the Console says the value was null, so that makes sense.

Uncaught TypeError: document.getElementById(…) is null

Now to just get the actual name of the page ‘Dive’ ‘Landscape’ if you’ve done it before.

document.title usually gets the content of the <title> element.
I use jquery more often, so you might need to look up what you’re trying to do.

Thanks, I’ll check it out.
One more thing if you don’t mind, moving the element to the bottom removed one error but I can’t find where else I’m calling getelementbyid

Uncaught TypeError: document.getElementById(…) is null

There was two of these. I checked my project settings.

Maybe it’s just a type error now

Thanks man. I found it (in the page settings).
Also that worked perfectly, just setting equal to document.title.
Learning! Gn