How to create HTML elements with JavaScript?

0

I have the following code JSFiddle

It creates a div that gives the information to insert and when calling the context menu with the direct button opens a box to insert an image.

My question is:

In part:

<div class="div-text" oncontextmenu="contextMenu(); return false;" contentEditable="true">
       <img src="" height="200" alt="Visualisar...">        
</div>

Edited:

Next I made a new one, now I can create a new element as soon as I right click, here's the example:

JSFiddle

    
asked by anonymous 21.09.2016 / 21:53

3 answers

4

You will not be able to read the file name directly but you can create a virtual path via the API URL.createObjectURL that the browser supports. In that case it would look like this:

function previewFile() {
    var preview = document.querySelector('img');
    var file = document.querySelector('input[type=file]').files[0];
    var caminhoVirtual = URL.createObjectURL(file);
    preview.src = caminhoVirtual;
}

jsFiddle: link

or simply URL.createObjectURL(event.target.files[0]); like this: link

    
21.09.2016 / 22:01
2

Wagner, create elements following a template, I advise you to use the tag.

In the example below I will clone a div.bloco and update the contents of it.

var tmplBloco = document.getElementById("tmplBloco").content;
var addBloco = document.getElementById("addBloco");
var contador = 1;

addBloco.addEventListener("click", function (event) {
  //criando fragmento.
  var content = document.importNode(tmplBloco, true);
  //procurando a div.bloco dentro do fragmento.
  var bloco = content.querySelector(".bloco");
  bloco.textContent = contador++;
  //adicionando o fragmento a pagina.
  document.body.appendChild(content);
});
.bloco {
  float: left;
  width: 32px;
  height: 32px;
  padding: 16px;
  line-height: 32px;
  font-size: 32px;
  text-align: center;
  margin: 10px;
  box-shadow: 0px 0px 10px black;
  background-color: white;
}
<input id="addBloco" type="button" value="adicionar bloco" />
<hr />
<template id="tmplBloco">
  <div class="bloco"></div>
</template>
    
21.09.2016 / 22:03
0

It would look like this in a simplified way:

var $div-text= document.querySelector('.div-text'),
    // Pega a string do conteúdo atual
    HTMLTemporario = $div-text.innerHTML,
    // Novo HTML que será inserido
    HTMLNovo = '<img src="" height="200" alt="Visualisar...">';

// Concatena as strings colocando o novoHTML antes do HTMLTemporario
HTMLTemporario = HTMLNovo + HTMLTemporario;

// Coloca a nova string(que é o HTML) no DOM
$div-text.innerHTML = HTMLTemporario;
    
21.09.2016 / 22:01