Aaron Shen Aaron Shen - 1 year ago 86
HTML Question

Is there any difference between "value" attribute to be empty and no value attribute at all in html?

Is there any difference between the following?

<input value/>
<input value=""/>
<input />

Answer Source

Yes there are differences, but only between two firsts and last one : from specs

Note that empty attribute syntax is exactly equivalent to specifying the empty string as the value for the attribute.

JS wise: two first will make getAttribute return an empty string, while last one will return null.
For all 3, value property will be an empty string.

CSS wise, input[value] will match only the 2 firsts.

var inp = document.querySelectorAll('input'),
for (var i = 0; i < inp.length; i++) {
  attr = inp[i].getAttribute('value')
  console.log(i, 'attr:', '[' + typeof attr + '] ' + attr, 'val:', '[' + typeof inp[i].value + '] ', inp[i].value);
input[value] {
  background: red;
<input value/>
<input value="" />

But note that this is only for <input> tag.
Other elements have other behaviours (e.g MediaElement and the controls attribute)

var vid = document.querySelectorAll('video'),
for (var i = 0; i < vid.length; i++) {
  attr = vid[i].getAttribute('controls')
  console.log(i, 'attr:', '[' + typeof attr + '] ' + attr,  'val:', '[' + typeof vid[i].controls + '] ', vid[i].controls);
<video controls></video>
<video controls=""></video>
<video controls="true"></video>
<video controls="false"></video>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download