-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 ?

2
  • 2
    stackoverflow.com/questions/5629684/… Commented Nov 5, 2018 at 6:32
  • const header = document.getElementById('#header'); should just give a null result. You can test if (header) before using it Commented Nov 5, 2018 at 6:48

2 Answers 2

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) { ... }
Sign up to request clarification or add additional context in comments.

Comments

-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.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.