Including javascript into an html file is easy, but is it possible to go the other way? If I have a test.html file
<html>
<head>
<script>
function helloWorld() { console.log("Hello World!"); }
</script>
</head>
<body>
<h1 id="test">TEST</h1>
</body>
</html>
I want to be able to include this html in javascript so that I can reference all of the DOM elements and javascript of my html file, i.e.
require("test.html");
var header = document.getElementById("test");
helloWorld();
This code obviously does not work. But I'd really like to find a way to include an html file in javascript as if it were the document object. Is this possible?
You can perform an AJAX call to test.html in your javascript code.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//xhttp.responseText will have all the HTML content
}
};
xhttp.open("GET", "test.html", true);
xhttp.send();
I don't have the context on why you want to do this but I don't recommend it. If you include your script into your HTML code, that script will be able to get any HTML node in that file.
Example:
<html>
<body>
<h1 id="test">TEST</h1>
</body>
<script>
//document.getElementById/getElementByClassName, etc will work with any node inside this file.
</script>
This is the same code from your question, except that the script is at the bottom and will work for you to get any elements.
With jQuery:
jQuery.get('https://example.caom/test.html', function(data) {
alert(data);
});
With vanilla js:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.caom/test.html');
xhr.onreadystatechange = function() {
xhr.responseText;
}
xhr.send();
I would do something like this.
https://codesandbox.io/s/happy-frog-pmidw?file=/src/index.js
const url = "test.html";
fetch(url)
.then((response) => response.text())
.then((text) => new DOMParser().parseFromString(text, "text/html"))
.then((dom) => dom.getElementById("test"))
.then((test) => {
console.log(test);
//Do something with test.
});