inspired this question , dealing similar situation, wonder whether can explain rationale behind decision have element.id return empty string when id attribute not present.
if spec return null
or undefined
write
var allids = $('#my-frm input').map(function() { return this.id; }).get();
instead have either add qualifier selector, in
var allids = $('#my-frm input[id]').map(function() { return this.id; }).get();
or use other solution proposed above-mentioned question (which has id twice in case present)
var allids = $('#my-frm input').map(function() { return (this.id) ? this.id : null; }).get();
or can use jquery attribute getter, seems unnecessary wrap each element jquery object first, i'm mentioning completeness , show jquery went other direction .attr() method.
var allids = $('#my-frm input').map(function() { return $(this).attr('id'); }).get();
i'm curious if there practical reason behind javascript element.id behavior.
update:
i located relevant spec, defines current behavior (it doesn't explain why defined way)
https://www.w3.org/tr/2015/rec-dom-20151119/#element
interface element : node { readonly attribute domstring? namespaceuri; readonly attribute domstring? prefix; readonly attribute domstring localname; readonly attribute domstring tagname; attribute domstring id; attribute domstring classname; ...
either when element created has id
attribute value not empty string or when element's id
attribute set value other empty string, set element's id new value.
when element's id
attribute removed or set empty string, unset element's id.
some idl attributes defined reflect particular content attribute of given name. means on getting, these steps must run:
get attribute context object using content attribute's name , let value result.
if value null, return empty string.
return value.
on setting, set attribute context object using name of attribute , given value.
the id
attribute must reflect "id
" content attribute.
i'm curious if there practical reason behind javascript element.id behavior.
see element.id
the
element.id
property represents element's identifier, reflectingid
global attribute.
if spec return
null
orundefined
identifiers opaque strings. particular meanings should not derived value of id attribute.
note there no other restrictions on form id can take; in particular, ids can consist of digits, start digit, start underscore, consist of punctuation, etc.
note element's unique identifier can used variety of purposes, notably way link specific parts of document using fragment identifiers, way target element when scripting, , way style specific element css.
it's funny how result kind of opposite of intent. because want avoid calling separate method check existence of
id
to substituting $.map()
.map()
, array.prototype.filter()
parameter boolean
.get()
return id
not empty string
var allids = $.map($("input"), function(el) { return el.id }).filter(boolean);
jsfiddle https://jsfiddle.net/gqvfuzqr/
Comments
Post a Comment