Reputation: 445
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?
Upvotes: 4
Views: 27699
Reputation: 253318
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:
Upvotes: 0
Reputation: 3040
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);
Upvotes: 2
Reputation: 15115
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>
Upvotes: 0