The id attribute assigns an identifier to an HTML element.
The id must be unique, and a page can only have one element with that id.
Ids are used by JavaScript and can also be used for CSS styling.
A <p> element with an id attribute.
A paragraph with an id.
<p id="my-paragraph"
style="background-color:aliceblue;padding:15px;">
A paragraph with an id.
</p>
Tip: The id must be unique on the page.
An id can only be used once on a page, whereas a class can be used multiple times.
In CSS, classes are defined with a dot (.) and ids are defined with a hash (#).
Dot (.) and hash (#) selectors are called class selectors and id selectors respectively.
Two selectors: an id selector and a class selector -- each one styling a <div>.
<style>
#alice { background-color: aliceblue; border: 1px solid #aaa; padding: 25px; }
.mint { background-color: mintcream; border: 1px solid #aaa; padding: 25px; }
</style>
<div>
<div id="alice">
The id of this div is alice -- #alice in CSS.
</div>
<br />
<div class="mint">
The class of this div is mint -- .mint in CSS.
</div>
</div>
HTML bookmarks allow users to jump to specific locations on a web page.
Bookmarks are useful in long web pages. Their URLs are defined by an id prefixed with a #
.
The link below scrolls the page to item 5 when clicked. The link is #item5
.
Note: It's difficult to demonstrate bookmarks in a small box. It works best on a full page.
<div><a href="#item5">Jump to Item 5</a></div>
<br />
<br />
<div id="item1">Item 1 content</div>
<div id="item2">Item 2 content</div>
<div id="item3">Item 3 content</div>
<div id="item4">Item 4 content</div>
<div id="item5">Item 5 content</div>
Note: Bookmarks are also refered to as anchors.
JavaScript can access an element by id with the getElementById()
method.
Clicking the button calls a JavaScript function that locates the <div> by id and changes its text.
<div id="world-id">Hello World!</div>
<br />
<button onclick="toggle();">Toggle Text</button>
<script>
let toggle = () => {
let element = document.getElementById("world-id");
if (element.innerHTML === "Hello World!") {
element.innerHTML = "Hello Earth!";
} else {
element.innerHTML = "Hello World!";
}
}
</script>