Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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">

<script>
    var e = $element.find('input')[0];
    if(!e.hasOwnProperty("placeholder")){...}
</script>

To my understanding, this should always be

if(!e.hasAttribute("placeholder")){...}

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

like image 481
NDavis Avatar asked Jan 04 '16 23:01

NDavis


People also ask

Should you use hasOwnProperty?

In general, hasOwnProperty() is the right choice most of the time, because you avoid issues with special keys, like constructor . A good rule of thumb is that if you're looking to see whether an object has a property, you should use hasOwnProperty() .

What is the use of hasOwnProperty in JavaScript?

The hasOwnProperty() method returns true if the specified property is a direct property of the object — even if the value is null or undefined . The method returns false if the property is inherited, or has not been declared at all.

Has attribute in JavaScript?

The hasAttribute() returns a Boolean value that indicates if the element has the specified attribute. If the element contains an attribute, the hasAttribute() returns true; otherwise, it returns false .


1 Answers

hasAttribute()

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>

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

hasOwnProperty()

hasOwnProperty() works only for JavaScript objects and returns true if that object has a 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.

like image 147
Ian Ramos Avatar answered Oct 17 '22 19:10

Ian Ramos