What Is an HTML Attribute?
An HTML attribute is a name-value pair that you can add to an element’s opening tag.
HTML attribute is an optional property of an element used to change the element’s behavior or provide extra information about it.
Syntax of an HTML Attribute
Section titled “Syntax of an HTML Attribute”HTML attributes typically have the form name="value"
. Here is the syntax:
<tagName attribute-name="value"></tagName>
Example: An Anchor Tag with Two Attributes
Section titled “Example: An Anchor Tag with Two Attributes”The HTML snippet below defines an anchor tag (<a>
) with href
and target
attributes.
<a href="https://codesweetly.com" target="_blank"> Visit CodeSweetly's Homepage</a>
Note that boolean attributes—such as required
, readonly
, disabled
, and check
—permit the omission of a value.
Example: An Input Tag with a disabled
Boolean Attribute
Section titled “Example: An Input Tag with a disabled Boolean Attribute”The HTML snippet below defines an input tag (<input>
) with a disabled
attribute.
<input type="color" value="#ba55d3" disabled />
Let’s now see how to create custom attributes.
How to Create Custom HTML Attributes
Section titled “How to Create Custom HTML Attributes”You can use the HTML data attribute to create custom attributes.
Example 1: An <input>
element with a custom data attribute
Section titled “Example 1: An <input> element with a custom data attribute”The HTML snippet below defines an <input>
element with a custom HTML attribute.
<input type="button" value="Click Me to Buy" data-test-btn="dummy-btn" />
Example 2: A <li>
elements with custom HTML attributes
Section titled “Example 2: A <li> elements with custom HTML attributes”The HTML snippet below defines three list elements with custom HTML attributes.
<h1>2021 U.S. News Best Countries Ranking</h1><ol> <li data-first-best-country="north-american">Canada</li> <li data-second-best-country="asia">Japan</li> <li data-third-best-country="europe">Germany</li></ol>