The global attributes of HTML5 (such as 'class', 'id', 'data-*', etc.)
HTML5 global attributes are common features shared by all HTML elements. They can be applied to any tag to provide additional information or control the element's behavior. These attributes are widely used in development to enhance page interactivity, accessibility, and style control.
class Attribute
The class
attribute is used to assign one or more class names to an element, typically combined with CSS to control the element's styling. Multiple class names are separated by spaces.
<div class="container main-theme">Content Area</div>
CSS can target these class names to apply styles:
.container {
width: 80%;
margin: 0 auto;
}
.main-theme {
background-color: #f0f0f0;
}
Class names are also commonly used in JavaScript for DOM manipulation:
const elements = document.querySelectorAll('.main-theme');
elements.forEach(el => {
el.style.border = '1px solid #ccc';
});
id Attribute
The id
attribute provides a unique identifier for an element. Each id
value should be unique within a page. It is often used for anchor links or precise JavaScript element selection.
<section id="user-profile">
<h2>User Information</h2>
</section>
CSS can style elements using the ID selector:
#user-profile {
padding: 20px;
}
JavaScript retrieves an element by its ID:
const profileSection = document.getElementById('user-profile');
profileSection.classList.add('active');
data-* Attributes
Custom data attributes allow developers to store additional information in HTML, formatted as data-
followed by a custom name. These attributes can be accessed via JavaScript but do not affect page rendering.
<button data-user-id="12345" data-action="delete">Delete User</button>
JavaScript reads data attributes:
const button = document.querySelector('button');
console.log(button.dataset.userId); // "12345"
console.log(button.dataset.action); // "delete"
Dataset properties also support camelCase access:
<div data-user-profile-id="A1001"></div>
const div = document.querySelector('div');
console.log(div.dataset.userProfileId); // "A1001"
style Attribute
The style
attribute is used for inline CSS styling, which takes precedence over external stylesheets. It is suitable for dynamic modifications or overriding styles for specific elements.
<p style="color: red; font-size: 16px;">Warning Message</p>
JavaScript manipulates the style
attribute:
const warning = document.querySelector('p');
warning.style.fontWeight = 'bold';
Note: CSS property names must use camelCase in JavaScript:
element.style.backgroundColor = 'blue'; // Correct
element.style.background-color = 'blue'; // Incorrect
title Attribute
The title
attribute provides additional information about an element, typically displayed as a tooltip on hover.
<abbr title="HyperText Markup Language">HTML</abbr>
<img src="logo.png" title="Company Logo">
For accessibility, screen readers may read the title
content, so it should not be the sole source of critical information.
lang Attribute
The lang
attribute declares the language code of the element's content, aiding search engines and screen readers in processing the content correctly.
<html lang="zh-CN">
<p lang="en">This paragraph is in English.</p>
Language codes follow ISO standards, such as:
- zh-CN: Simplified Chinese
- zh-TW: Traditional Chinese
- en: English
- ja: Japanese
dir Attribute
The dir
attribute specifies text direction, with possible values:
ltr
: Left-to-right (default)rtl
: Right-to-leftauto
: Determined by the browser
<p dir="rtl">هذا نص باللغة العربية</p>
hidden Attribute
A Boolean attribute indicating whether the element should be hidden. Equivalent to setting display: none
.
<div hidden>This content will not be displayed</div>
JavaScript controls visibility:
document.getElementById('element').hidden = true; // Hide
document.getElementById('element').hidden = false; // Show
tabindex Attribute
Controls whether an element is focusable and its order in Tab key navigation:
tabindex="0"
: The element is focusable in DOM order.tabindex="-1"
: The element can be programmatically focused but is excluded from the Tab sequence.tabindex="1"
or higher: Higher priority in focus order (not recommended).
<div tabindex="0">Focusable div</div>
<button tabindex="-1">Button excluded from Tab sequence</button>
contenteditable Attribute
Makes the element's content editable. The value is a Boolean or an empty string (treated as true
).
<div contenteditable="true">
Click here to edit this text.
</div>
JavaScript checks the editable state:
const editableDiv = document.querySelector('div');
console.log(editableDiv.isContentEditable); // true
draggable Attribute
Controls whether the element is draggable, used with the Drag and Drop API:
true
: Draggablefalse
: Not draggableauto
: Browser default behavior
<img src="image.jpg" draggable="true" id="drag-image">
JavaScript drag-and-drop example:
const img = document.getElementById('drag-image');
img.addEventListener('dragstart', (e) => {
e.dataTransfer.setData('text/plain', img.id);
});
spellcheck Attribute
Controls whether spell-checking is enabled for the element's content:
true
: Enable spell-checkingfalse
: Disable spell-checking
<textarea spellcheck="true"></textarea>
<p contenteditable spellcheck="false">Editable but no spell-check</p>
accesskey Attribute
Specifies a shortcut key for the element. The key combination varies by browser (typically Alt + key).
<button accesskey="s">Save (S)</button>
On Windows, pressing Alt + S usually triggers this button.
contextmenu Attribute
Specifies a context menu for the element (deprecated; use JavaScript instead).
<div contextmenu="popup-menu">Right-click here</div>
<menu type="context" id="popup-menu">
<menuitem label="Refresh"></menuitem>
</menu>
dropzone Attribute
Defines the behavior of an element as a drop target (experimental feature):
copy
: Data will be copied.move
: Data will be moved.link
: Data will generate a link.
<div dropzone="copy"></div>
translate Attribute
Indicates whether the element's content should be translated:
yes
: Should be translated (default)no
: Should not be translated
<p translate="no">Brand Name</p>
inputmode Attribute
Hints to the browser which input mode to display on virtual keyboards:
none
: No virtual keyboardtext
: Text input keyboarddecimal
: Numeric keyboard with a decimal pointnumeric
: Numeric-only keyboardtel
: Telephone number keyboardsearch
: Search-optimized keyboardemail
: Email-optimized keyboardurl
: URL-optimized keyboard
<input type="text" inputmode="numeric">
is Attribute
Used to specify a custom element's prototype:
<button is="fancy-button">Fancy Button</button>
Requires JavaScript definition:
class FancyButton extends HTMLButtonElement {
constructor() {
super();
this.style.backgroundColor = 'pink';
}
}
customElements.define('fancy-button', FancyButton, { extends: 'button' });
Other Boolean Attributes
HTML5 includes several Boolean attributes, where their presence indicates true
:
<video controls autoplay muted>
<source src="movie.mp4" type="video/mp4">
</video>
<form novalidate>
<input type="email" required>
</form>
<details open>
<summary>Details</summary>
<p>More content...</p>
</details>
Common Boolean attributes include:
autofocus
: Automatically focuses the element on page loaddisabled
: Disables the elementreadonly
: Makes the input control read-onlymultiple
: Allows multiple selections (for file uploads or<select>
)required
: Marks a form field as mandatoryautoplay
: Media autoplayscontrols
: Displays media controlsloop
: Media loopsmuted
: Media is mutedplaysinline
: Media plays inline (iOS)default
: Default track for<track>
elementschecked
: Checkbox or radio button is selectedselected
:<option>
is selectednovalidate
: Form does not validateformnovalidate
: Submit button overrides form validationopen
:<details>
,<menu>
, or<dialog>
elements are initially expanded
Custom Global Attributes
Developers can create custom attributes, but it is recommended to use the data-*
format to avoid conflicts with future HTML standards. Non-standard attributes may fail validation.
<div custom-attribute="value"></div>
JavaScript access:
const div = document.querySelector('div');
console.log(div.getAttribute('custom-attribute')); // "value"
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:HTML5的标签语法规则
下一篇:HTML5的字符编码设置