简体   繁体   中英

Same DOM elements on different HTML pages

i think my question is a little bit stupid, but I have a problem. There`sa 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?

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM