Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

So I feel like this should be a common question but I can\'t find the answer. Ma

ID: 647448 • Letter: S

Question

So I feel like this should be a common question but I can't find the answer. Maybe I'm using the wrong terminology.

Assumptions:

IDs are supposed to be unique across the document.

Class attributes are meant for CSS and should not be used in JS selectors.

Name attributes are not appropriate ID replacements since they don't work the same on all elements and the html 5 spec changed them (removed from certain elements I think).

So given something like:

The page has multiple of the same widget. Each widget has a unique ID. I need to be able to reference widget sub-elements like $("#widgetID relativeID"). So that relative IDs are unique within widgets but may be duplicated outside this scope.

I had been using name for this but it seems this isn't the correct way

What is?

Explanation / Answer

You first and third assumptions are solid. You middle assumption "class attributes are meant for CSS and should not be used in JS selectors" is completely, utterly wrong. Granted, there's some structural / separation-of-concerns purity about it. But it rejects the reality and common practice of almost all dynamic JavaScript modification of HTML documents.

If you only have one of a thing on a page, and you know that's not going to change, the id attribute works well for both CSS and JS. When there are possibly more than one of a thing, the class attribute is precisely the place to note this. jQuery and all other modern "higher level JavaScript" libraries bake this kind of usage right into their code, documentation, and examples, and everyone uses class selectors in this way.

Relative ids are not a standard part of either CSS or JS parlance, and they probably never will be. The very idea suggests taking something that is absolute and making it relative. Given the availability, success, and ubiquity of class selectors, what would be the point? If you want to simulate that kind of access, define unique class selectors and then use the relative (e.g. child, descendant, or adjacent sibling) notation that's already part-and-parcel of CSS and JS usage.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote