Could somebody explain exactly how this feature detection is working?
// Create a dummy element for feature detection
if (!('placeholder' in $('<input>')[0])) {
This line of code detects whether or not the browser supports the placeholder attribute on input elements.
I’d like to be a bit more comfortable with what is going on under the hood here before deploying to production.
Will this end up cycling through all possible attributes of the input element, just to check for the existence of a placeholder element? If this is the case, I was not aware that we get access (in some fashion) to elements that aren’t spelled out explicitly in the markup.
You have access to any element created with javascript, regardless of whether or not that element is appended to the page itself or not. So if you create an element, you can change it, like so:
Now to create an element in jQuery you do:
and of course the
[0]at the end gets the native DOM element, so these two are exactly the same:Once you have created an element, all properties of that element are available as well, such as
element.valueetc.If the browser supports placeholders, the placeholder attribute will be present on an input element, and since the element we created is in fact a node or element object, we use the
inkeyword to check if that property is available:another way to do the same thing would be to check the property directly to see that it’s not undefined, like so: