javascript does not create html element and does not add to the page

2

I'm starting in javascript and wanted to create html elements dynamically but when I load the page it goes blank and does not add the elements code below:

function add (){

    var texto = document.createTextNode("teste");
    var p = document.createElement("p");
    var ptexto = p.appendChild(texto);
    var body = document.getElementsByTagName("body")[0];
    body.appendChild(ptexto);

}
    
asked by anonymous 02.10.2017 / 17:19

1 answer

4

I think you want to insert p and not ptexto right?

Anyway, your code works, see here:

function add() {
  var texto = document.createTextNode("teste");
  var p = document.createElement("p");
  var ptexto = p.appendChild(texto);
  var body = document.getElementsByTagName("body")[0];
  body.appendChild(ptexto);
}

add();

But I think what you want is:

function add() {
  var texto = document.createTextNode("teste");
  var p = document.createElement("p");
  var ptexto = p.appendChild(texto);
  document.body.appendChild(p);
}

add();
p {
  background-color: #eef;
  padding: 5px;
}

And in this case you do not need textNode , you can do this:

function add() {
  var p = document.createElement("p");
  p.textContent = 'teste!!';
  document.body.appendChild(p);
}

add();
p {
  background-color: #eef;
  padding: 5px;
}
    
02.10.2017 / 17:23