-3

Is it possible to have elements with the same ID on two different pages?

How do jQuery selectors work in such cases?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Teknoville
  • 459
  • 1
  • 7
  • 18
  • What kind of application is it? it can work if it's NOT a single page application – grvpanchal Nov 11 '18 at 07:18
  • How is this question a duplicate of that one? This one is asking about elements with the same ID on two different pages entirely. Or were the duplicate votes cast based on a misconception that the unique ID restriction extends across multiple pages? – BoltClock Nov 11 '18 at 09:06

2 Answers2

2

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:

  • A single CSS style definition
  • A single HTML template for the dynamic element
  • An anticipated similarity in subsequent event handling logic

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).

user1063287
  • 10,265
  • 25
  • 122
  • 218
0

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356