Element Attributes
What are Element Attributes in HTML?
An HTML element can have attributes. HTML element's attributes are appended to its opening tag or its sole tag.
ID & Class
Two of the most commonly used attributes are id and class.
Both id and class can be used for:
- selecting the element for styling in CSS (
#forid,.forclass), - selecting the element in JavaScript (
getElementByIdforid,getElementsByClassName().forclass)
Further, id can be used for fragment identifier linking i.e. linking to a specific place in a document.
The difference between id and class is that:
- in a given HTML document there can be only one element with a given
idwhereas there might be an unlimited number of elements with a givenclass, - a given HTML element can only have one
idhowever an unlimited number of classes
<body>
<div id="horses" class="names, coloration">
...
</div>
<div id="witchers" class="names, schools">
...
<div>
</body>Style
An HTML attribute can be styled in two ways:
- through selecting in CSS and applying respective styling,
- through applying inline styling using the
styleattribute.
<p style="background:black;color:white;">
White text on black background.
</p>Nowadays, using inline styling is discouraged in favor of CSS.
Global Attributes
id, class and style are examples of global attributes i.e. attributes common to many HTML elements.
Other notable HTML global attributes are:
autofocus- indicates the element to be focused once the page loads,hidden- prevents the element from rendering,lang- indicates the element's content language,tabindex- indicates the sequential position inTabkey navigation,title- a description of the element which might be presented as a tooltip by a user agent, and- event handlers such as
onblur,onchange,onclick,onfocus,onkeydown,onkeypress,onkeyup,onmousedown,onmouseenter,onmouseleave,onselect,onsubmit.