-2

I want to create a dynamic title for my website using HTML and JavaScript. However, I'm getting an error in the developer console that says 'TypeError: null is not an object (evaluating 'document.getElementById("send").addEventListener')'. I want to understand why it's not reading the objects in the JavaScript-defined array.

JS:

var titles = ["My website", "Glad to see you!", "Have a nice day!"];
 var index = 0;

 function changeTitle() {
    document.getElementById("title").innerText = titles[index];
    index = (index + 1) % titles.length;
  }
  setInterval(changeTitle, 7000);

HTML : <title id="title">My website</title>

  • 1
    I do not see `document.getElementById("send").addEventListener` mentioned in your code snippet. Also, when does the script run, in the head or the body, is it deferred? You need more information. – Mr. Polywhirl Jul 12 '23 at 14:47
  • [Works for me](https://jsfiddle.net/nwjru6g3/). I don't see how that error is related to the code shown. Can you provide a runnable [mcve] which demonstrates the problem? – David Jul 12 '23 at 14:48
  • Thank you for your attention. It is working inside the script body, but when I try adding 'defer' to the script tag for it to run last, it doesn't work.' – Utku karagül Jul 12 '23 at 14:52
  • Can you edit your code snippet to include the line of code that throws the error. Otherwise its difficult to figure out what exactly is happening. Also add the line where you add your js script to your html. – Milind Mohapatra Jul 12 '23 at 14:55
  • https://stackoverflow.com/questions/413439/how-to-dynamically-change-a-web-pages-title – epascarello Jul 12 '23 at 15:08

1 Answers1

2

You should not declare a <title> inside the <body>. It is reserved for the document's <head>. It specifies the actual tab/window title for the webpage.

const customTitleEl = document.getElementById("title");
const titles = ["My website", "Glad to see you!", "Have a nice day!"];
let currentIndex = 0;

function changeTitle() {
  customTitleEl.textContent = titles[currentIndex];
  currentIndex = (currentIndex + 1) % titles.length;
}
changeTitle(); // Call it initially
setInterval(changeTitle, 1000); // Update every "second"
<!-- The <title> should be declared in the document <head> (only once!) -->
<!-- Use a <div> inside the <body> instead -->
<div id="title">My website</div>

If you actually want to update the webpage's title, call:

document.title = 'My new title';
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132