Search code examples
javascripthtmldominternet-explorer-7extend

JavaScript: Implement 'element.hasAttribute' if undefined [for IE7]


I need to make an exisitng web application compatible with IE7.

The code uses element.hasAttribute extensively and IE7 has issues with this method.

Object doesn't support property or method 'hasattribute'

I am trying to check in the code if an input element has the hasAttribute method defined and if not, I am trying to add it to all input elements.

//create an input element variable << works fine
var myInput = document.createElement("input");

//see if it has the 'hasAttribute' method << condition works fine
if (('hasAttribute' in myInput)==false)
{

    //get all input elements into objInputElements <<works fine
    var objInputElements=document.getElementsByTagName("input");

    // MORE CODE NEEDED - To implement a hasAttribute function for all 
    // elements in the array probably using something
    // like: !!element[attributeName] which works in IE7. See link and notes below.
}

This article describes how to define a seperate function to do this. However, I would like to add the hasattribute method to the elements if it is not defined. (this way I don't need to change all the code that is currently written)

IMPORTANT NOTE: There are > 1000 hidden input fields in the form therefore, the 'hasattribute' method needs to be added to the elements in a very efficient way.

Please let me know the how I could achieve this. Thank you!


Solution

  • Since Element.prototype is not supported IE < 8, there is no efficient way to polyfill hasAttribute. The inefficient way (if you wanted to avoid shimming) would be something like this (placed after all inputs had loaded):

    <input data-abc="" />
    <script>
    
    if (!window.Element || !window.Element.prototype || !window.Element.prototype.hasAttribute) {
    
    (function () {
        function hasAttribute (attrName) {
            return typeof this[attrName] !== 'undefined'; // You may also be able to check getAttribute() against null, though it is possible this could cause problems for any older browsers (if any) which followed the old DOM3 way of returning the empty string for an empty string (yet did not possess hasAttribute as per our checks above). See https://developer.mozilla.org/en-US/docs/Web/API/Element.getAttribute
        }
        var inputs = document.getElementsByTagName('input');
        for (var i = 0; i < inputs.length; i++) {
            inputs[i].hasAttribute = hasAttribute;
        }
    }());
    
    }
    
    var inputs = document.getElementsByTagName('input');
    document.write(
        'has?' + inputs[0].hasAttribute('abc') // false
    );
    document.write(
        'has?' + inputs[0].hasAttribute('data-abc') // true
    );
    
    </script>