1

i think my question is a little bit stupid, but I have a problem. There`s a few html pages, for ex.: index.html and rooms.html etc... And a main.js file with scripts for all .html pages. The problem is that i have a variables, like

const HTMLelement = document.querySelector('.className');

and some functions to work with this HTMLelement. But, this element is only on index.html page, and when im on rooms.html page, i have an error, cause HTMLelement is not defined and other script does not exists (its important, cause some html build by script.) Also, in main.js I have scripts for all pages, so I cant create new .js file... So, what is the best way to separate scripts for different html pages?

  • 1
    Why not just check if that element actually exists, before trying to perform any further operations on it ...? – CBroe Jan 19 '18 at 15:16
  • so, I just need to check if(HTMLelement) { //some code } is this ok? – Артем Мирошниченко Jan 19 '18 at 15:17
  • "Also, in main.js I have scripts for all pages, so I cant create new .js file..." without further information, that argument doesn't hold – rollstuhlfahrer Jan 19 '18 at 15:17
  • Why does `main.js` contain `all` of the `javascript` from all the pages? Simply chop it up into more files. Make `one file` that has functions for `repeatable content` and include it in `all the HTML` files that need it. Then make `other files` with `page specific functions` where needed and add them only to the `HTML pages for which they were written`. – Ivan86 Jan 19 '18 at 15:25
  • Split your JS into parts. One script for the functions that you want to share on all pages and one script for each page that takes care of the page-specific things. – Shilly Jan 19 '18 at 15:25

2 Answers2

2

Here you have several ways to solve the issue

Create specific separate script for each page

  • rooms.html -> rooms.js
  • index.html -> index.js

Checking the existence of nodes before you do something

if(document.querySelectorAll('.className').length == 0){
     // do things
}

Checking the current page before you do something

if(window.location.pathname.indexOf('rooms.html') != -1){
     // do things
}

Hope it helps

Shalitha Suranga
  • 1,138
  • 8
  • 24
0

Always validate that an element exists before you try to use it.

const oneEl = document.querySelector('.one');
if (oneEl) {
  oneEl.setAttribute('title', 'This is one');
}

// Below I am trying to get an element by the wrong class name.
const twoEl = document.querySelector('.two');
if (twoEl) {
  // This code will not run
  twoEl.setAttribute('title', 'This is two');
}
<div class="one">One</div>
<div class="too">Two</div>
Intervalia
  • 10,248
  • 2
  • 30
  • 60