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

Asked

Viewed 73 times

2

I’m starting at the javascript and wanted to create html elements dynamically but when you 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);

}

1 answer

3

I think you want to insert the p and not the 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 that case you don’t need textNode, you can do it like this:

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

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

  • thanks everyone, I tried to run in the browser but it did not appear, and it appears a msg the time I inspect the page appears Uncaught Typeerror: Cannot read Property 'appendchild' of Undefined would be something of configuration?

  • Sergio and I think you want to remember, I see that beautiful Song, https://www.youtube.com/watch?v=Rr7TaaJ60Ws

  • @Leocaracciolo :)

  • 1

    @Markup This appears if you are adding Javascript inside the head. Place at the end of body or with window.load = function(){ /* o código aqui */ }

  • 1

    @Marceosdourado Asssim: [seu html] ... <script src="..."></script></body></html>

Browser other questions tagged

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