larryq
larryq

Reputation: 16299

Using CSS selector to find an element with same ID as another, but different class

I'm working with an HTML document that uses a lightbox implementation for image viewing, and for reasons relating to its API it uses the same element ID in two spots-- one for the thumbnail view and one for the lightbox/full view. (These elements are in separate <div> tags.)

The two elements have different class values, and I was wondering how to differentiate them when writing selectors? Is it something like #myElementWithDuplicateID.className1 and #myElementWithDuplicateID.className2?

In general, is it bad practice to use the same ID for different elements on a page, or are there situations for doing it I'm not aware of?

Upvotes: 1

Views: 510

Answers (1)

BoltClock
BoltClock

Reputation: 723408

Duplicate IDs are not valid in an HTML document, and will cause issues with scripting especially, so their use is widely considered bad practice. There aren't any situations where having elements with a common ID is justified over having a common class instead. You should correct the duplicate IDs if you can to prevent potential complications with your lightbox API and elsewhere.

That said, in a situation where you can't de-duplicate the IDs, your proposed solution (chaining ID and class selectors) will work. A lone ID selector in CSS will match all elements with a given ID regardless of whether or not they're duplicates, so using a class selector to differentiate them is reasonable. Further reading.

Upvotes: 2

Related Questions