Is the ID attribute on an HTML element allowed to be empty?
<div id=""></div>
I'm using a template where the ID of the element is set by a variable which may not always have a value and I'm wondering if this could cause any unforeseen problems.
EDIT: The "variable" is actually an editable region (block) in a Django template. This means I can't put any conditional logic on it.
<div id="{% block id %}{% endblock %}">
Rather than:
<div {% block id %}{% endblock %}>
Which would have to be inherited in the sub-template as:
{% block id %}id="whatever"{% endblock %}
IDs for HTML elements can't be blank. The <label> element represents a caption in a document, and it can be associated with a form input using the for attribute, which must be an ID.
id 's value must not contain whitespace (spaces, tabs etc.). Browsers treat non-conforming IDs that contain whitespace as if the whitespace is part of the ID. In contrast to the class attribute, which allows space-separated values, elements can only have one single ID value.
Note: In HTML5, id attributes can be used by any HTML tag but in HTML 4.01 there are some restriction to use id attributes. It can not be used by <base>, <head>, <html>, <meta>, <param>, <script>, <style>, and <title> tag.
No, it is not necessary. It is required only when you have to access any form control uniquely on a web page.
According to the W3C:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
(Source: Basic HTML data types)
This would indicate that a blank value for the attribute is not valid in accordance with the above definition.
Trying to validate against an empty ID attribute returns the following:
syntax of attribute value does not conform to declared value
<div id="">something</div>
The value of an attribute contained something that is not allowed by the specified syntax for that type of attribute. For instance, the “selected” attribute must be either minimized as “selected” or spelled out in full as “selected="selected"”; the variant “selected=""” is not allowed.
Even if no browser will crash on empty IDs, if you wanna generate valid HTML, you should generate fake IDs and differents, say, prefix + counter.
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