Home >Web Front-end >CSS Tutorial >Why Do Duplicate IDs in HTML Sometimes Work, and What's the Best Practice?
#red { color: red; }
<p><p>Despite the duplicate IDs, both paragraphs will appear red in all major browsers. However, this behavior is not guaranteed and can lead to unexpected side effects. <p>For example, accessing the element by its ID using document.getElementById('red') will only return the first element. To select both elements, you would need to use an attribute selector like document.querySelectorAll('p[id="red"]'). However, this approach is not supported in IE7 and below. <p>To avoid potential issues, it is strongly recommended to use class names instead of IDs for targeting multiple elements with CSS. Class names are expressly designed for this purpose and ensure consistency across all browsers.
The above is the detailed content of Why Do Duplicate IDs in HTML Sometimes Work, and What's the Best Practice?. For more information, please follow other related articles on the PHP Chinese website!