Sometimes, we want to create label and check box dynamically in JavaScript.
In this article, we’ll look at how to create label and check box dynamically in JavaScript.
How to create label and check box dynamically in JavaScript?
To create label and check box dynamically in JavaScript, we can use the createElement
method.
For instance, we write:
const newLabel = document.createElement("label");
newLabel.setAttribute("for", 'checkbox');
newLabel.innerHTML = "Here goes the text";
const newCheckbox = document.createElement("input");
newCheckbox.setAttribute("type", 'checkbox');
newCheckbox.setAttribute("id", 'checkbox');
document.body.appendChild(newLabel);
document.body.appendChild(newCheckbox);
We call document.createElement
to create a label.
Then we call setAttribute
to set the for attribute to checkbox.
And we set the innerHTML
property to add some text to the label.
Next, we call createElement
again to create an input.
Next, we call setAttribute
to set the type attribute to checkbox to make it a checkbox.
We call the same method to set the id attribute.
Finally, we call document.body.appendChild
to append them both to the body element.
Conclusion
To create label and check box dynamically in JavaScript, we can use the createElement
method.