Incluir javascript en un archivo html es fácil, pero ¿es posible ir al otro lado? Si tengo un archivo test.html
<html> <head> <script> function helloWorld() { console.log("Hello World!"); } </script> </head> <body> <h1 id="test">TEST</h1> </body> </html>Quiero poder incluir este html en javascript para poder hacer referencia a todos los elementos DOM y javascript de mi archivo html, es decir
require("test.html"); var header = document.getElementById("test"); helloWorld();Este código obviamente no funciona. Pero realmente me gustaría encontrar una manera de incluir un archivo html en javascript como si fuera el objeto del documento. es posible?
Puede realizar una llamada AJAX a test.html en su código javascript.
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();No tengo el contexto de por qué quieres hacer esto, pero no lo recomiendo. Si incluye su secuencia de comandos en su código HTML, esa secuencia de comandos podrá obtener cualquier nodo HTML en ese archivo.
Ejemplo:
<html> <body> <h1 id="test">TEST</h1> </body> <script> //document.getElementById/getElementByClassName, etc will work with any node inside this file. </script>Este es el mismo código de su pregunta, excepto que el script está en la parte inferior y funcionará para que usted obtenga cualquier elemento.
Con jQuery:
jQuery.get('https://example.caom/test.html', function(data) { alert(data); });Con vainilla js:
var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://example.caom/test.html'); xhr.onreadystatechange = function() { xhr.responseText; } xhr.send();Yo haría algo como esto.
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. });