Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I want to append an existing div to have a particular design along with an error message extracted out of an array.

This was my attempt:

    if (data.errors.firstName) {
        document.getElementById("firstName").classList.add("has-error");
        document.getElementById("firstName-group").appendChild('<div class="help-block"> </div>');

But it resulted in an error:

TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

Which after researching means that is a string which I can add in as it is not a valid dom node.

How can I do this properly?

Your function is returning a string rather than the div node. appendChild can only append a node

var d= document.createElement("div");
d.classList.add("help-block");
document.getElementById("firstName-    group").appendChild(d);
document.getElementById("firstName").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
document.getElementById("firstName-group").appendChild(helpBlock);
.has-error {
  border: 1px solid red;
.help-block {
  border: 1px solid green;
.help-block::after {
  content: 'i am the help block';
<div id="firstName-group">
  <div id="firstName">first name</div>

As the error reports, parentNode.appendChild() requires a DomNode as its argument; however if you must pass HTML strings instead then you could, instead, use parentNode.append():

if (data.errors.firstName) {
    document.getElementById("firstName").classList.add("has-error");
    document.getElementById("firstName-group").append('<div class="help-block"> </div>');

Note, though, that this is considered by MDN – seethe linked reference, below – as “experimental,” so check compatibility before use.

References:

  • parentNode.append().
  • Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.