Same DOM elements on different HTML pages

824 Views Asked by At

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?

2

There are 2 best solutions below

0
Shalitha Suranga On

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

0
Intervalia On

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>