I have used
element.hasAttribute('id')
in my code to test whether the element has an attribute id. But hasAttribute API is only patible 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".
I have used
element.hasAttribute('id')
in my code to test whether the element has an attribute id. But hasAttribute API is only patible 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".
Share Improve this question edited Oct 31, 2013 at 13:46 Code Lღver 15.6k16 gold badges59 silver badges75 bronze badges asked Oct 31, 2013 at 13:43 Swaraj ChhatreSwaraj Chhatre 6671 gold badge10 silver badges22 bronze badges 2- Test the return value of getAttribute(). – Virus721 Commented Oct 31, 2013 at 13:45
- Answered here: codereview.stackexchange./questions/10131/… – Pat Dobson Commented Oct 31, 2013 at 13:47
2 Answers
Reset to default 7In 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.