Do I need to check if an element has an attribute?
I use data attributes in HTML elements
Example:
<div class="fruit" data-color="red">...</div> In jQuery, I get the data attribute using $(this).data("color") and adding it has the class name for the element.
Do I need to check first if the data attribute exists before adding it to the class? Example:
// $(this) is .fruit div if ( $(this).data("color") ) { $(this).addClass($(this).data("color")); //adds data value as class to element } or handles jQuery? I tried to run the code without an if statement, and I don't get any errors if the element does not have the "color" data attribute. I assume jQuery just ignores it.
jQuery handles this for you - in fact, it is very reliable in that it will accept for most method parameters without throwing any errors.
In this case, if the data attribute is not found (or does not matter), it will return undefined . If you then addClass(undefined) jQuery will not perform any actions on the selected elements.