JS - Connect <h1> with <title>

All I want to do is to make the title the exact same as the h1 tag.

<title class="blogtitle"></title>
<h1 class="title">Updating our staff members</h1>

<script>
        document.getElementsByClassName("blogtitle")[0].innerHTML = h1;
        var h1 = document.getElementsByClassName("title")
</script>

Solution 1:

That would be very bad for both SEO and accessibility. Don't use JS for this. Use a template engine that allows to do this on the server.

That being said, here's the Javascript that would do this and which you shouldn't use if search engine optimization or accessibily is of any relevance in your project.

document.addEventListener('DOMContentLoaded', // make sure this code only runs once JS can access the DOM safely
  function() { //
    document.title = document.querySelector('h1.title')?.textContent ?? '';
  }
);
<!DOCTYPE html>
<html lang="en">

<head>
  <title></title>
</head>

<body>
  <h1 class="title">Updating our staff members</h1>
</body>

</html>

Instead of using the DOMContentLoaded listener (which is only in place to make sure all the elements in the page are available for accessing via Javascript), you can also include your <script> tag right before the closing </body> tag:

<!DOCTYPE html>
<html lang="en">

<head>
  <title></title>
</head>

<body>
  <h1 class="title">Updating our staff members</h1>
  <script>
    document.title = document.querySelector('h1.title')?.textContent ?? '';
  </script>
</body>

</html>

Solution 2:

Well, it looks like you're just learning HTML and getting into this new universe. So I will just answer your question and not overload you with a bunch of advanced information.

You can change the title of a page by using

document.title = 'Your new title'

so you can do something along these lines:

var h1Element = document.getElementsByClassName("title")[0] // you can use other selectors here such as querySelector, getElementByClassName...
var h1Text = h1Element.innerHTML
document.title = h1Text

Also, you are not suposed to put a class into a title tag and it must be within a <head> tag.

Just remember the basic structure of a HTML:

<!DOCTYPE html>
<html>
<head>
   <title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>

</body>
</html>