Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda