0

I am trying to get an HTML element from 2 different html files. The problem is I only get one of them.

var message1 = document.getElementById("message1") works.

But when I try to do the same for the element in the other html page:

var message2 = document.getElementById("message2") it returns null

I have a main html file (index.html):

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <p id = "message1">I hate the post office</p>
    <script src="script.js"></script>
  </body>
</html>

And I also have another html file (page2.html):

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <p id = "message2">Random sentence</p>
    <script src="script.js"></script>
  </body>
</html>

And finally I have a javascript file (script.js):

//Gets message1 from index.html (works)
var message1 = document.getElementById("message1")
//logs message1 from index.html (works)
console.log(message1)

//gets message2 from page2.html (doesn't work)
var message2 = document.getElementById("message2")
//logs message2 from page2.html (logs null)
console.log(message2)

How do I get the elements of id message and message2 in script.js?

4
  • What do you mean by "secondary html file"? How is the secondary file included in the page? Commented Feb 20, 2021 at 14:26
  • Sorry about that, I meant another html file (edited). All 3 files listed are in one folder Commented Feb 20, 2021 at 14:30
  • Right, but is there anything telling the browser to download the second file and include it in the page in some way? Commented Feb 20, 2021 at 14:37
  • It's hosted on repl.it so I don't think I need to tell the browser to download the file Commented Feb 20, 2021 at 14:51

1 Answer 1

2

I try this another way using iframe. Add in index.html page

<p id="message">I hate the post office</p>
<iframe src="page2.html" frameborder="0" style="display: none;"></iframe>
<script src="script.js"></script>
Sign up to request clarification or add additional context in comments.

5 Comments

So I can't get both the elements in the same javascript file?
Try this @Dregg. This is the short solution.
I tried this but message2 still returns null. message1 still works. Do I need to change the javascript file after adding this iframe?
Nvm I tried opening it in a new tab and it worked. Thanks
I'm curious though, what's the long solution?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.