admin管理员组

文章数量:1307220

I use setAttribute to store some info on an element, so later I can restore the value to its innerHTML. My question is what exactly element.getAttribute("attr") return value will be when the attribute does not set (exist)?
It seems that it returns null in chrome (which is good for me), but I read it can return empty string too, but I want to use the value if empty string is set.

so I can't do this obviously:

var value = element.getAttribute("prev_value");
if (value) { // won't cover the empty string case, so I need value != null
}

Are there any browsers which do not returns null ?

I use setAttribute to store some info on an element, so later I can restore the value to its innerHTML. My question is what exactly element.getAttribute("attr") return value will be when the attribute does not set (exist)?
It seems that it returns null in chrome (which is good for me), but I read it can return empty string too, but I want to use the value if empty string is set.

so I can't do this obviously:

var value = element.getAttribute("prev_value");
if (value) { // won't cover the empty string case, so I need value != null
}

Are there any browsers which do not returns null ?

Share Improve this question asked Sep 8, 2016 at 15:38 user3599803user3599803 7,04421 gold badges77 silver badges137 bronze badges 4
  • 1 if (value) covers empty string case actually – Andrey Commented Sep 8, 2016 at 15:39
  • 2 How about not using invalid attributes at all, but stick with datasets – adeneo Commented Sep 8, 2016 at 15:39
  • 1 If you really want to use attributes you should check hasAttribute. – Prusse Commented Sep 8, 2016 at 15:40
  • 4 You can use element.hasAttribute() to check if element has attribute. – Maciej Wiercioch Commented Sep 8, 2016 at 15:40
Add a ment  | 

3 Answers 3

Reset to default 3

Basic usage of getAttribute()

"getAttribute() returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string); see Notes for details." - MDN Docs

As @Maciej pointed out, you should use .hasAttribute() to return your truthy value.

You should just use a typeof and see if it is an empty string

var value = element.getAttribute("prev_value");
if (typeof value == "string" && value.length) {
//..do something
}

But, actually making if("") returns false, same as if(null).

Element.getAttribute returns null or empty string if the attribute does not exist

if (object.getAttribute("prev_value") === null) {
//data attribute doesn't exist
 }else{
 //data attribute exists
}

Internet Explorer, browsers based on Gecko, browsers based on KHTML and not yet public releases of Opera all return null.

本文标签: javascriptgetAttribute return value when it does not existStack Overflow