Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to check if element has attribute?

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.

like image 631
CyberJunkie Avatar asked May 06 '15 19:05

CyberJunkie


People also ask

How do you know if an element has an attribute?

hasAttribute() The Element. hasAttribute() method returns a Boolean value indicating whether the specified element has the specified attribute or not.

How do you check if an HTML element has an attribute?

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 .

Which method is used to check if an attribute exists or not?

The hasAttribute() method returns true if the attribute exists, otherwise false .

What is the use of element attributes?

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.


1 Answers

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.

like image 70
Rory McCrossan Avatar answered Oct 28 '22 10:10

Rory McCrossan