When I implement this code - the name of the checkbox wont show up in the browser alongside the checkbox - just the checkbox itself. whats the reason for this? Am I using the setattribute-function incorrectly?
<script type="text/javascript">
var x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");
x.setAttribute("value", "car");
x.setAttribute("name", "vehicle");
document.body.appendChild(x);
</script>
The "setAttribute is not a function" error occurs for multiple reasons: calling the setAttribute() method on a value that is not a DOM element. placing the JS script tag above the code that declares the DOM elements. calling the setAttribute method on a jQuery object (should use attr() instead).
setAttribute() Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value. To get the current value of an attribute, use getAttribute() ; to remove an attribute, call removeAttribute() .
setAttribute('style', 'property: value'); And it works, but if that element already had styles applied, they will all get overwritten.
To set the disabled attribute, select the element and call the setAttribute() method on it, passing it disabled as the first parameter, e.g. button. setAttribute('disabled', '') . The setAttribute method will add the disabled attribute to the element. Here is the HTML for the examples in this article.
You need to add a label
element:
var x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");
x.setAttribute("value", "car");
x.setAttribute("name", "vehicle");
document.body.appendChild(x);
var label = document.createElement("label");
label.textContent = "vehicle";
document.body.appendChild(label);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With