Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hasAttribute("id") replacement before IE8

I have used

element.hasAttribute('id') 

in my code to test whether the element has an attribute id. But hasAttribute API is only compatible with browsers after IE8.Is there a similar API or technique which I can use to check the availability of an attribute for an element in my case "id".

like image 530
Swaraj Chhatre Avatar asked Jan 13 '23 00:01

Swaraj Chhatre


2 Answers

In the absence of the hasAttribute method, you need to use getAttribute. This should return null if there is no attribute set, and an empty string otherwise. In practice, some browsers return an empty string, so there's no way in these browsers of telling whether it is an empty attribute or no attribute at all.

if ((element.getAttribute('id') === null) || (element.getAttribute('id') === '')) {
like image 101
lonesomeday Avatar answered Jan 21 '23 14:01

lonesomeday


Just check element.id - it'll be an empty string if it's not set.

There's no need to use element.hasAttribute for those attributes that are mirrored by JS object properties.

like image 25
Alnitak Avatar answered Jan 21 '23 15:01

Alnitak