How to add one element inside another

0

What am I doing wrong in my example?

var t = document.querySelector("#t");

t.prependChild('<div class="verde"></div>');
#t{
  width: 300px;
  background: red;
 height: 300px; 
}
.verde{
   background: green;
    width: 30px;
    height: 30px;
    display: block; 
}
.roxo{
   background: purple;
    width: 30px;
    height: 30px;
    display: block; 
}
<div id="t">
  <div class="roxo"></div>
</div>
    
asked by anonymous 02.04.2018 / 21:27

3 answers

3

There are a few ways to add an HTML element / code inside, outside, before, or after an element. One is with the insertAdjacentHTML method. With it you can use HTML code, without the need of createElement .

element.insertAdjacentHTML("posição", "código-html");

To control where you want the element, simply add one of the values below instead of position

  

Beforebegin: Before Element

  

afterbegin: Inside the element and before your first child

  

beforeend: Inside the element and after your last child

  

afterend: After the

Example:

var t = document.querySelector("#t");

t.insertAdjacentHTML('beforebegin', '<div class="verde"></div>');
#t{
  width: 300px;
  background: red;
 height: 300px; 
}
.verde{
   background: green;
    width: 30px;
    height: 30px;
    display: block; 
}
.roxo{
   background: purple;
    width: 30px;
    height: 30px;
    display: block; 
}
<div id="t">
  <div class="roxo"></div>
</div>
    
02.04.2018 / 21:45
1

Two things you did wrong:

  • Try to use a prependChild method that does not exist
  • Try to pass a string to this method.
  • Shortest Solution

    var t = document.querySelector("#t");
    t.innerHTML = '<div class="verde"></div>' + t.innerHTML;
    

    Solution without innerHTML (usually more efficient)

    var t = document.querySelector("#t");
    var div = document.createElement('div');
    div.className = 'verde';
    t.insertBefore(div, t.firstChild);
    
        
    02.04.2018 / 21:36
    1

    The prependChild method does not exist, at least not natively.

    You can create your own method as an extension of Element.prototype :

    var t = document.querySelector("#t");
    var div = document.createElement("div");
    div.classList.add("verde");
    
    
    //Espera receber um nó como parâmetro
    Element.prototype.prependChild = function prependChild(element) {
        this.insertBefore(element,this.firstChild); 
    };
    
    
    t.prependChild(div);
    #t{
      width: 300px;
      background: red;
     height: 300px; 
    }
    .verde{
       background: green;
        width: 30px;
        height: 30px;
        display: block; 
    }
    .roxo{
       background: purple;
        width: 30px;
        height: 30px;
        display: block; 
    }
    <div id="t">
      <div class="roxo"></div>
    </div>
        
    02.04.2018 / 21:54