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".
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') === '')) {
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With