admin管理员组

文章数量:1352840

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?

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?

Share Improve this question asked Oct 20, 2018 at 23:08 kawekikaweki 4452 gold badges5 silver badges8 bronze badges 1
  • Possible duplicate of Issue with appendChild in JS – Shireesha Parampalli Commented Oct 21, 2018 at 6:55
Add a ment  | 

3 Answers 3

Reset to default 2

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);

You can't pass a string value to appendChild, it has to be a Node which you can create using document.createElement, like so:

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>
</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 patibility before use.

References:

  • parentNode.append().

本文标签: