一下的代碼是我從國(guó)外的網(wǎng)上看的,我又改進(jìn)了一點(diǎn),在這跟大家分享
代碼
- document.getElementsByAttribute = function(attribute,parent) {
- return $A(($(parent) || document.body).getElementsByTagName('*')).inject([],function(elements,child){
- if(Element.readAttribute(child,attribute)!=null)
- //這個(gè)判斷我改成了!=null原來(lái)沒(méi)有但這樣當(dāng)你在元素中只是添加了某個(gè)屬性
- //如<input type='text' required />這時(shí)原來(lái)的代碼就會(huì)找不到
- elements.push(Element.extend(child));
- return elements;
- });
- }
- document.getElementsByAttributeValue = function(attribute,value,parent) {
- return $A(($(parent) || document.body).getElementsByTagName('*')).inject([],function(elements,child){
- if(Element.readAttribute(child,attribute) == value)
- elements.push(Element.extend(child));
- return elements;
- });
- }
- Element.addMethods({
- getElementsByAttribute: function(element,attribute){
- return document.getElementsByAttribute(attribute,element);
- },
- getElementsByAttributeValue: function(element,attribute,value){
- return document.getElementsByAttributeValue(attribute,value,element);
- }
- });
使用時(shí)
代碼
- <html>
- <head>
- <script src='prototype.js'></script>
- <script src='prototype.tidbits.js'></script>
- <script language="javascript" type="text/javascript">
- Event.observe(window,'load',function(){
- alert($('div1').getElementsByAttribute('require').length);
- alert(document.getElementsByAttribute('require').length);
- })
- </script>
- </head>
- <body>
- <div id='div1'>
- <input type='text' require/>
- <input type='text' require />
- </div>
- </body>
- </html>