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
3 Answers
Reset to default 2Your 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()
.
本文标签:
版权声明:本文标题:javascript - TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type &a 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743904034a2559193.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论