How to add one element inside another

Asked

Viewed 1,191 times

0

What I’m 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>

  • 1

    The prependChild method doesn’t exist, that’s what’s wrong.

  • How do I make it work?

3 answers

4


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

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

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

beforebegin: Before the Element

afterbegin: Inside the element and before your first child

beforeend: Inside the element and after your last child

afterend: After the element

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>

  • 1

    lol, I didn’t know the insertAdjacentHTML

  • Bring a myth to this Oscar named Valdeir. Ball show this insertAdjacentHTML.

1

Two things you did wrong:

  1. Trying to use a method prependChild that doesn’t exist
  2. Try passing 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);

1

The method prependChild 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.