Is it possible to have elements with the same ID on two different pages?
How do jQuery selectors work in such cases?
Is it possible to have elements with the same ID on two different pages?
How do jQuery selectors work in such cases?
An id needs to be unique on one page.
The intention of assigning an id
to an element, as opposed to a class, is to say:
this element has a unique identity
If two elements on separate pages are representative of the same data, however, it is acceptable for them to have the same id
, for example:
page_1.html
<div id="title">About Me</div>
page_2.html
<div id="title">My Projects</div>
Conversely, if the elements on two pages represent different data, and you assigned them the same id
, whilst technically valid, it may make it difficult to understand your code at a later date, for example:
page_1.html
<div id="contact">My Name</div>
page_2.html
<div id="contact">click to contact</div>
As an example of a scenario where one might be tempted to use the same id
for elements with different data, I share the following experience in case it helps anyone think though a similar situation...
I recently tried to be "clever" by assigning a dynamically injected element into a page with the same id
(an <input>
element in an editing content scenario), regardless of its location (programatically it was only ever present in the page once).
The pros of this approach were:
However I found I always needed a way to identify the instance uniquely, and so I ended up using data attributes that indicated the unique instance.
It got pretty complicated pretty quickly and I kind of regretted my approach and still wonder if assigning a unique id
would have made the program logic simpler (but I don't have time to refactor at the moment).
If each of the elements with the same ID resides on its own page, then jQuery will only ever see one element at a time, since only one such element with that ID exists in each page context at a time. It's as simple as that.