simmerjs icon indicating copy to clipboard operation
simmerjs copied to clipboard

Simmer returns an Attribute selector for IDs instead of an ID Selector

Open jasheal opened this issue 6 years ago • 4 comments

Expected Behaviour as per docs:

const EL = document.getElementById('uniqueElementId');
const selector = simmer(EL);

console.log(EL) // prints 'uniqueElementId' 

Actual Behaviour:

const EL = document.getElementById('uniqueElementId');
const selector = simmer(EL);

console.log(EL) // prints '[id='uniqueElementId']' 

I can't see any docs anywhere that refer to this output format....

jasheal avatar Mar 20 '18 13:03 jasheal

Hi Jason, Thanks for filing the issue.

This is actually the expected behaviour, and I'll explain why: When you provide an element to Simmer it tries to calculate a selector which will return the provided element. When it comes to IDs there are two ways in which to refer to a specific element:

  1. An ID selector, such as "#uniqueElementId"
  2. an attribute selector such as "[id='uniqueElementId']" (You can read about these selectors here)

Both of these are actually saying the same thing, which is "Give me the element which has a attribute named 'id' and who'se value is 'uniqueElementId'".. That said there is a difference between them - the first option returns the first element on the page with the given ID, while the second will return all the elements with that ID. Simmer uses the property selector in order to make sure that if the page has two elements with the same ID on them, then it will in fact reject the usage of ID all together (as that is actually an invalid state and we would prefer to generate a selector which is reliable, rather than one that just coincidentally works).

You could argue that if choose to use the ID as a selector then we could convert it to a "#uniqueElementId" selector instead of "[id='uniqueElementId']", but there is no technical reason to do so (that I'm aware of) rather an aesthetic one, but we've also found the property selector to be easier to read when the final selector is made out of longer and more complex queries, so we would prefer to keep the property selector approach.

I hope this helps. :)

gmmorris avatar Mar 21 '18 15:03 gmmorris

I will make sure to better document this for the future - thanks for bringing this to my attention

gmmorris avatar Mar 21 '18 15:03 gmmorris

Thanks for the detailed answer!

Your reasoning to output the attribute selector over the actual ID string itself makes sense to me now :)

jasheal avatar Mar 21 '18 23:03 jasheal

Brilliant, I'm glad to hear it. I'll keep the issue open to remind myself to add this to the documentation.

Cheers

gmmorris avatar Mar 23 '18 16:03 gmmorris