How to add div before another div with JavaScript

3

I'm having trouble getting a new div before another or just adding a div, but with JavaScript.

Example:

I already have a DIV

<div class="primeira"></div>

I want to add one above it with Javascript, thus:

<div class="div-adicionada"></div>
<div class="primeira"></div>
    
asked by anonymous 28.09.2017 / 16:38

2 answers

2

You can use the insertAdjacentHTML a>.

The first parameter is the position you want to insert, use beforebegin to add before. You can see all possible values in the documentation .

The second parameter is the string HTML that should be inserted.

const div = document.getElementsByClassName('primeira')[0];  
div.insertAdjacentHTML('beforebegin', '<div class="segunda">Segunda div</div>');
<div class="primeira">Primeira div</div>
    
28.09.2017 / 19:21
0

use the Node.insertBefore(newNode, referenceNode) method.

var primeira = document.querySelector(".primeira");
var divAdicionada = document.createElement("div");

divAdicionada.classList.add("div_adicionada");
divAdicionada.textContent = "Div Adicionada";

primeira.parentElement.insertBefore(divAdicionada, primeira);
<div class="div_qualquer">Div qualquer</div>
<div class="primeira">Primeira</div>
    
28.09.2017 / 19:19