I'm using data attributes in HTML elements
Example:
<div class="fruit" data-color="red">...</div>
In jQuery I'm getting the data attribute using $(this).data("color")
and adding it has a class name to the element.
Is it necessary to validate first if a data attribute exists before adding it as a class? Example:
// $(this) is .fruit div
if ( $(this).data("color") ) {
$(this).addClass($(this).data("color")); //adds data value as class to element
}
or does jQuery handle that? I tried running the code without the if statement and I don't get any errors if the element has no "color" data attribute. I'm guessing that jQuery just ignores it.
hasAttribute() The Element. hasAttribute() method returns a Boolean value indicating whether the specified element has the specified attribute or not.
To check if an HTML element has any attributes, you can use the hasAttributes() method. This method returns true if the specified node has any attributes, otherwise false . If the specified node is not an Element node, for example, whitespace and comments, the return value is always false .
The hasAttribute() method returns true if the attribute exists, otherwise false .
The Element. attributes property returns a live collection of all attribute nodes registered to the specified node. It is a NamedNodeMap , not an Array , so it has no Array methods and the Attr nodes' indexes may differ among browsers.
jQuery handles that for you - in fact it's very robust in what it will accept for most method parameters without throwing any errors.
In this case if the data
attribute is not found (or has no value) it will return undefined
. If you then addClass(undefined)
jQuery will perform no action on the selected elements.
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