Uncaught Typeerror: Cannot read Property 'appendchild' of null

Asked

Viewed 725 times

0

I researched about and they said it was because HTML was being loaded before JS vice versa, the solution was to change the place of the calls of the scripts, I pasted in everything that is place and nothing

<div id="content">
    <b id="bt_cad">cadastre se</b>
</div>

var content = document.getElementById('content');
bt_cad.click(function() {
    log.css("display", "none");
    cad.css("display", "block");

    var c_form_cad = document.createElement('form');
    c_form_cad.method="post";
    c_form_cad.id="form_cad";
    c_form_cad.autocomplete="off";

    // erro no appendChild
    document.getElementById(c_form_cad.id="form_cad").appendChild(content);

    console.log(content);
    console.log(c_form_cad);
});
  • 1

    It’s always good to reference a id using, or document.getElementById or document.querySelector, instead of doing so bt_cad.click. I mean, it would be document.getElementById("bt_cad").click or document.querySelector("#bt_cad").click.

1 answer

1


Looking at your code the problem is that c_form_cad (form) was created but was not added to the page yet document.getElementById will return null.

Another point is that in this case the c_form_cad is already the element you want so there is no need to make a document.getElementById, just use the c_form_cad.

// document.getElementById(c_form_cad.id="form_cad").appendChild(content);
c_form_cad.appendChild(content);


// não esqueça de adicionar a pagina, algo parecido como o comando abaixo
document.body.appendChild( c_form_cad );

another thing taking a second look may be that you want to do the opposite, ie add the form within the div#content if that is the case the correct code would be

content.appendChild( c_form_cad );
  • man just one more thing in that line c_form_cad.id="form_cad" attribute id, cannot assign an class tbm? I tried so c_form_cad.class="form_cad";

  • 1

    has yes using c_form_cad.className="form_cad";

Browser other questions tagged

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