简体   繁体   中英

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 />

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'), attr; 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="" /> <input> 

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

 var vid = document.querySelectorAll('video'), attr; 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM