Access Multiple Elements of same ID in jQuery

前端 未结 4 698
离开以前
离开以前 2020-11-29 11:15

If i have elements such as this




         


        
4条回答
  •  借酒劲吻你
    2020-11-29 12:04

    It is true that having multiple elements with the same id is incorrect. However it is pretty easy to generate such code in general-purpose frameworks, for example in Django one may have more than one forms in a single view with the same field auto_id. Thus it would be nice to have jQuery function which selects all of these elements so client-side Javascript code can check the length of returned list and trigger a client-side error / warning in such case.

    Also do not forget that the value of id has to be escaped in CSS query. While recent versions of Chrome / Firefox have native support of CSS.escape(), IE may require a polyfill: https://github.com/mathiasbynens/CSS.escape

    $.id = function(id) {
        // FF 54 generates warning when empty string is passed.
        if (typeof id !== 'string' || id === '') {
            return $();
        } else {
            // Support multiple ID's to detect content bugs.
            return $(document.querySelectorAll('#' + CSS.escape(id)))
        }
    };
    

提交回复
热议问题