NDavis NDavis - 4 years ago 170
HTML Question

hasAttribute vs hasOwnProperty

I ran into some jquery code which attempts to use hasOwnProperty to access an html attribute.

<input type="text" name="fname" placeholder="First name">

var e = $element.find('input')[0];

To my understanding, this should always be


but what is the difference between hasAttribute and hasOwnProperty? Are they ever equivalent?

Answer Source


hasAttribute() works only for html elements and returns true if that element has the same attribute name as the given argument.

<div class="myClass"></div>

    document.querySelector('div').hasAttribute('class'); //true
    document.querySelector('div').hasOwnProperty('class'); //false


hasOwnProperty() works only JavaScript objects and returns true if that object has an property with the same name as the given argument.

var obj = {
    myProp: "my attribute"

obj.hasOwnProperty("myProp") //true
obj.hasAttribute("myProp") //false

Some html elements can be constructed inside javascript, thats why hasOwnProperty works sometimes for it, but hasAttribute never works for javascript objects.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download