Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

113
Vistas
Import HTML to dynamically add elements using JS

I will be dynamically adding elements to my main index.html using .innerHTML += "<p>example</p>"; However I do not want to store the large html-like string in this .js file, but instead import it from another file example.html

example.html:
<p>example</p>

(It is just a snippet of code and not a standalone html file, but I want to keep the .html extension for linting, autocompletion and general readability)

My attempts:

$(...).load('example.html'): did not work as it replaces of contents of ... with this example instead of appending it

import * from example.html: this and other attempts of importing file failed because of MIME error that text/html cannot be imported

I will be perfectly satisfied with a solution of a method that reads .html as text and returns it as a string (preferably not using AJAX or ES6 as I do not feel confident with them). I would then just use the string in .innerHTML += imported_string; and call it a day.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

If I correctly understand what you want to do, you can use FileReader to import the content of a file and convert it to text, for example:

function readFile(event) {

  var file = event.target.files[0];

  var stream = new FileReader();
  stream.onload = function(e) {
    var fileContent = e.target.result;
    alert(fileContent);
  }
  stream.readAsText(file);

}

document.getElementById('myFile').addEventListener('change', readFile, false);
<input type="file" accept="html" id="myFile">

The file input is for presentation purposes, you can easily adapt this to your needs.

You should also perform the customary checks, which I ommited for brevity purposes.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Create a fetch request to the file that you want to retrieve. This is, in a basic sense, the same way how a browser would request a html file from the server.

The function below sends a request based on what you input as a file. For example, 'example.html'. It then checks if the request was a success and returns the response as a string. The string can then be appended to your innerHTML.

const getFileAsText = async file => {
  const response = await fetch(file);
  
  if (!response.ok) {
    throw new Error(`Fetching the HTML file went wrong - ${response.statusText}`);
  }

  return response.text();
};

You can use it like the example below.

getFileAsText('example.html').then(html => {
  document.body.innerHTML += html;
});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda