Print div with appendChild

0

I'm trying to print with appendChild, without it being necessary to mount using document.createElement, I know it's possible but I do not know how, with innerHTML working but it deletes everything, below:

var div = "<div id='teste'>valorqualquer</div>";
document.getElementsByTagName("body")[0].appendChild(div);

// But it displays the message below:

Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

I've tried this (but it does print text only):

div =  document.createTextNode(div);  

document.getElementsByTagName("body")[0].appendChild(div);

Look at the structure I need to mount:

<div id="erroDeCampos" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
    <div class="modal-dialog modal-sm" role="document"> 
        <h3 class="center">Campos com erro:</h3>                  
        <div class="alert alert-danger">
            <strong>Erro!</strong> You should <a href="#" class="alert-link">read this message</a>.
        </div>  
    </div>
</div>

For each field that my form will display this structure will be created, but to do this I think it would look like a very large code, it follows part of the code:

var divElement = document.createElement("div");
divElement.setAttribute("id", "erroDeCampos");
divElement.setAttribute("class","modal fade bs-example-modal-sm");
divElement.setAttribute("tabindex", "-1");
divElement.setAttribute("role", "dialog");
divElement.setAttribute("aria-labelledby", "mySmallModalLabel");    

var divElementModalAninhado = document.createElement("div");
divElementModalAninhado.setAttribute("class", "modal-dialog modal-sm");
divElementModalAninhado.setAttribute("role", "document");

var h3ElementAninhado = document.createElement("div");
h3ElementAninhado.setAttribute("class", "center");
h3ElementAninhado.innerHTML = "Campos com erro";

var divaninhadoaoh3acima = document.createElement("div");
    
asked by anonymous 30.07.2017 / 23:14

2 answers

0

You can not understand your restrictions well. You need to pass a DOM knot pro appendChild , no use passing text. This works, I do not know if it caters to you:

var div = document.createElement('div');  
div.id = 'teste';
div.innerHTML = 'valor qualquer <strong>valendo HTML</strong>';
    
document.body.appendChild(div);
    
30.07.2017 / 23:34
0

For this you should use the method insertAdjacentHTML()

Example usage:

elemento.insertAdjacentHTML(posição, texto);

Positions:

beforebegin Before the element. beforebegin Inside the element before your first child (childNode). beforeend Within the element, after its last child (childNode). afterend After the element.

Demo:

var div = '<div id="teste">valorqualquer</div>';
document.body.insertAdjacentHTML( 'beforeend', div );
Corpo da página!!!
  

Check the documentation for browser compatibility.

Link to the documentation

01.09.2017 / 10:30