Main Differences
Uniqueness:
- id: An id must be unique within an HTML document. This means each id identifies a single element.
- class: A class can be shared by multiple elements. This is to identify a group of elements with similar styles or behaviors.
Purpose:
- id: Due to its uniqueness, id is commonly used to identify a specific element on the page, which is helpful when using JavaScript or CSS, especially when you need to manipulate or style a particular element.
- class: Due to its reusability, class is suitable for defining styles for a group of elements or applying the same behavior to multiple elements.
CSS and JavaScript Selectors:
- In CSS, you can select an element with a specific id using the
#symbol, e.g.,#navbar. The.symbol is used to select all elements with a specific class, e.g.,.button. - In JavaScript, you can use
getElementById()to retrieve an element with a specific id, andgetElementsByClassName()to retrieve a collection of elements with a specific class.
Example
Assume you are creating a webpage with multiple buttons, but one button has a special function, such as submitting a form.
HTML code might look like this:
html<button class="button">Cancel</button> <button class="button" id="submit-button">Submit</button> <button class="button">Clear</button>
In this example:
- All buttons share the same basic styling, so they have a common class named
button. - The submit button has a unique function (submitting the form), so it also has an id named
submit-button, which we can use to add specific event handlers or styles.
In CSS, we might write:
css.button { padding: 10px; background-color: blue; color: white; font-size: 16px; } #submit-button { font-weight: bold; box-shadow: 0 4px 8px rgba(0,0,0,0.2); }
In JavaScript, adding special functionality to the submit button:
javascriptdocument.getElementById('submit-button').addEventListener('click', function() { alert('Form has been submitted!'); });
This example clearly demonstrates the different uses of id and class and how they are applied in actual development.
2024年8月7日 18:09 回复