Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an ID allowed to be empty in an HTML tag?

Tags:

html

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 %} 
like image 729
Soviut Avatar asked Jun 30 '11 13:06

Soviut


People also ask

Can ID be empty HTML?

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.

Can ID in HTML have space?

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.

Can you give HTML tag an ID?

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.

Is ID necessary in HTML?

No, it is not necessary. It is required only when you have to access any form control uniquely on a web page.


2 Answers

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.

like image 77
Jamie Dixon Avatar answered Sep 22 '22 19:09

Jamie Dixon


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.

like image 33
ern0 Avatar answered Sep 20 '22 19:09

ern0