最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - hasAttribute vs hasOwnProperty - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited Jan 5, 2016 at 7:03 T J 43.2k13 gold badges86 silver badges142 bronze badges asked Jan 4, 2016 at 23:05 NDavisNDavis 1,2272 gold badges16 silver badges23 bronze badges 1
  • 1 They are equivalent when the attribute is mirrored by a property, like some HTLM attributes are. – adeneo Commented Jan 4, 2016 at 23:05
Add a ment  | 

2 Answers 2

Reset to default 15

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.

HTML:

<span medium-img>Whatever</span>

Javascript:

alert($('span').is('[medium-img]')); // Alerts true
发布评论

评论列表(0)

  1. 暂无评论