10

I want to programmatically create a selected HTML select option using Javascript (not jQuery). What are the merits of creating it by setting the attributes as follows:

var option = document.createElement('option');
option.setAttribute('text', 'option1');
option.setAttribute('value', 5);
option.setAttribute("selected", true);

as opposed to setting properties:

var option = document.createElement('option');
option.text = 'option1';
option.value = 5;
option.selected = true;

I'd prefer to create the options using properties but just want to be sure that this isn't going to cause any issues, as many of the examples I've come across on the web tend to favour using the former approach (i.e. setting attributes).

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
aw1975
  • 253
  • 2
  • 10
  • 1
    Possible duplicate of http://stackoverflow.com/questions/6003819/properties-and-attributes-in-html – Buzinas Sep 24 '15 at 16:01

3 Answers3

1

setAttribute should be used on DOM elements and lowercases the attribute name on HTML elements. You can't use dot notation to assign values to dynamic attribute names.

Using setAttribute() to modify certain attributes, most notably value in XUL, works inconsistently, as the attribute specifies the default value. To access or modify the current values, you should use the properties. For example, use elt.value instead of elt.setAttribute('value', val).

So in summary, use setAttribute if you have dynamic attribute names. If you have normal attributes, use dot notation.

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
0

setAttribute will add (create) the attribute if it does not exist yet and set the value, while the short hand functions work if the attribute is compatable with the DOM object. I believe none of them is "better" to use, there are just shorthands for the attributes being used often for convenience.

I think it is completely based on the preference of the user and depending on what attributes you want to set.

Niki van Stein
  • 10,564
  • 3
  • 29
  • 62
-1

It may be important to note that when using option.setAttribute('text', 'foo');, rather than setting the innerHTML, it will instead create a new property named text (e.g. <option text='foo'>).

The obj.setAttribute() function is useful when setting undocumented attributes, however in this instance it would be best to use option.text = 'foo';

N J
  • 27,217
  • 13
  • 76
  • 96