3

I try the follow -

var input = document.createElement("<input type='checkbox' name='test'>")

but it prompt -

Uncaught InvalidCharacterError: The string contains invalid characters. 

I use Chrome Version 33.0.1750.146 m

URL87
  • 10,667
  • 35
  • 107
  • 174
  • 1
    See the doc http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-2141741547 – gernberg Mar 06 '14 at 22:04
  • MDN usually has nice explanation of DOM methods: https://developer.mozilla.org/en-US/docs/Web/API/document.createElement – Ian Mar 06 '14 at 22:04

2 Answers2

6

You create the plain element and then add the attributes:

var input = document.createElement("input");
input.type = "checkbox";
input.name = "test";
Unihedron
  • 10,902
  • 13
  • 62
  • 72
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • 1
    You could also use input.setAttribute('type','checkbox'). That way you can set all attributes you want. – Nicky Smits Mar 06 '14 at 22:07
  • 1
    This is _not_ setting attributes, it is setting shorthand attribute properties, i.e. properties that reflect attribute values. @NickySmits Shorthand properties are to be preferred; one notable exception are `data-*` attributes, and attributes in XML namespaces. – PointedEars Mar 06 '14 at 22:16
  • I know what you are saying. but both methods work. And if the person decides to add some onclick action, he could do it within a string, which might be easier than an anonymous function (since this person is learning the basics) – Nicky Smits Mar 06 '14 at 22:19
0

The document.createElement function takes a tag name for the element you want to create (in your case input)

var input = document.createElement("input");

you can then access attributes for that element like so:

input.type = "checkbox";
input.name = "test";

Here is another question with the same answer: How to create <input type=“text”/> dynamically

Community
  • 1
  • 1
dinkydani
  • 151
  • 9