jQuery hasAttr checking to see if there is an attr

2018-12-31 19:16发布

Possible Duplicate:
Check existence of an attribute with JQuery

How do you check if there is an attribute on an element in jQuery? Similar to hasClass, but with attr?

For example,

if ($(this).hasAttr("name")) {
    // ...
}

标签: jquery
9条回答
梦该遗忘
2楼-- · 2018-12-31 20:14

Late to the party, but... why not just this.hasAttribute("name")?

Refer This

查看更多
骚的不知所云
3楼-- · 2018-12-31 20:16

You're so close it's crazy.

if($(this).attr("name"))

There's no hasAttr but hitting an attribute by name will just return undefined if it doesn't exist.

This is why the below works. If you remove the name attribute from #heading the second alert will fire.

Update: As per the comments, the below will ONLY work if the attribute is present AND is set to something not if the attribute is there but empty

<script type="text/javascript">
$(document).ready(function()
{
    if ($("#heading").attr("name"))
      alert('Look, this is showing because it\'s not undefined');
    else
      alert('This would be called if it were undefined or is there but empty');
});
</script>
<h1 id="heading" name="bob">Welcome!</h1>
查看更多
时光乱了年华
4楼-- · 2018-12-31 20:17

The best way to do this would be with filter():

$("nav>ul>li>a").filter("[data-page-id]");

It would still be nice to have .hasAttr(), but as it doesn't exist there is this way.

查看更多
登录 后发表回答