Skip to content
Advertisement

Getting elements from multiple html pages into javascript

I have two html pages called home.html and about.html. And I also have a js file called main.js which is linked with both of the html pages.I have a div with a class of “home” in home.html and another div with a class of “about” in about.html. Class “home” has a text and class “about” has a text too.Now I slected them in my main.js file like this,

const home = document.querySelector('.home')
const about = document.querySelector('.about')

And manipulated them like this,

home.style.color = 'red'
about.style.color = 'green'

But the problem is only the variable ‘home’ is changing its color not the variable ‘about’

I think there is maybe a particular way to select elements from multiple pages. But if there is pls let me know bcz the variable ‘about’ is not getting manipulated with anything.

const home = document.querySelector('.home')
const about = document.querySelector('.about')

// Manipulated them like this
home.style.color = 'red'
about.style.color = 'green'
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>ES8 Project</title>
  <link rel="stylesheet" href="main.css" /> </head>

<body>
  <div class="home"> HOME </div>
  <script src="main.js"></script>
</body>

</html>

Advertisement

Answer

Rather than:

<div class="home"> HOME </div>
<div class="about"> ABOUT </div>

You can use a custom data attribute like data-page:

<div data-page="home"> HOME </div>
<div data-page="about"> ABOUT </div>

Then, if you want to do something more dynamic than straightforward CSS styling, you can script the following:

const myDiv = document.querySelector('[data-page]');

switch (myDiv.dataset.page) {

  case ('home') : [... DO SOMETHING... ] ; break;
  case ('about') : [... DO SOMETHING... ] ; break;
}

N.B. When using this setup, where you do only want to apply CSS styling, then definitely use CSS:

[data-page="home"] {
  color: red;
}

[data-page="about"] {
  color: green;
}

Further Reading:

Advertisement