1

There is a <h1 id="title">Title</h1> in a html file. Now if I want to change its content from a js file. I always do this:

var el = document.getElementById("title");
el.innerHTML = "Hello world!";

But Now, I am able to do this:

title.innerHTML = "Hello world!";

I want to know if the second method is okay because everywhere it is mentioned to go with the first method and there is no mention of the second method anywhere?

K. Jadon
  • 21
  • 1
  • 4
    It's something that slipped into browser's years ago and is considered a bad development practice. Technically, you can call an HTML object by referencing its ID in JavaScript -- however, you run into problems with reserved words and with how IDs can be formatted. It's always better to use `.getElementById()` – Doug Apr 05 '18 at 13:20
  • 2
    And, don't use `.innerHTML` when you aren't setting/getting strings with HTML in them. Use `.textContent` for those. – Scott Marcus Apr 05 '18 at 13:23
  • @Dough Thanks and please make your comment as an official answer so that I can close this question. – K. Jadon Apr 05 '18 at 14:22

0 Answers0