-2

Lets say i have 2 html pages ( home & about ), inside the home page i have a header like so

<header id="#header">
  some code
</header>

and this header is only on the home page so if i selected this header in java script main file

const header = document.getElementById('#header');

it's going to give me an error on about page because there is no such a thing as header in this page, so how do you prevent those kind of errors ? do I have to make it a local variable instead ?

what I actually made is something like this

if( body.className = 'home' ) {
 some code
}

like this I will be sure that about page won't have access to anything that related to the home page, but is this is a bad practice ?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Taste of Leaving
  • 304
  • 2
  • 20

2 Answers2

0

There are many ways that this could be improved. The most direct answer to your question though is that document.getElementById returns null if the element is not found. So put any code that depends on header in a conditional that checks for null.

if (header) { ... }
murrayju
  • 1,752
  • 17
  • 21
-1

You can use ternary operator in javascript like

const header = document.getElementById('#header')?document.getElementById('#header'):null;

Hence it will not give error, and wherever you want to use it you can use a null check using if statement.

Abbas Ali
  • 1
  • 1
  • This is not a great use of the ternary operator. This same line would be better reduced to `const header = document.getElementById('#header') || null;`, but this is still unnecessary because `document.getElementById` either returns a DOM node or `null` itself. – murrayju Nov 06 '18 at 19:47