Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use HTML5 data-* attributes as boolean attributes? [duplicate]

I want to use a custom boolean attribute to mark an element's contents as editable. I'm aware of the data-* attributes, but wasn't sure if they require a value. I don't need data-is_editable="false", as the lack of the attribute would be equivalent. I only care if it's "true" (if the attribute exists). I know I can use other attributes like class but I don't want to as it seems slightly inappropriate (correct me if I'm wrong about that).

Here's the resource I'm reading, maybe it's the wrong document or I've overlooked the information I'm looking for: http://www.w3.org/html/wg/drafts/html/master/dom.html#custom-data-attribute

So for example, is this legal and valid?

<div data-editable data-draggable> My content </div> 
like image 578
Wesley Murch Avatar asked May 31 '13 20:05

Wesley Murch


People also ask

Can data -* attribute contain HTML tags?

The data-* attribute is a Global Attribute, and can be used on any HTML element.

Which attribute is a Boolean attribute?

A Boolean attribute is an attribute that can only be true or false. How does a Boolean attribute work? According to the HTML specification: The presence of a boolean attribute on an element represents the “true” value, and the absence of the attribute represents the “false” value.

Can you have multiple data attributes?

A data attribute is a custom attribute that stores information. Data attributes always start with “data-” then followed with a descriptive name of the data that is being stored. You can have multiple data attributes on an element and be used on any HTML element.

How do you add a Boolean attribute in HTML?

To add a Boolean attribute: node. setAttribute(attributeName, ''); // example: document. body.


1 Answers

The example you show is valid. (Just like using disabled or checked in a form. Only xHTML force the presence of a value)

Although, the value returned is not a boolean. When you query this resource, you'll get an empty string for any empty data-* attributes.

Like so:

 domNode.dataset.draggable; // log ""  domNode.dataset.notAdded; // log null 

So, you just have to check it:

var isDraggable = (domNode.dataset.draggable != null) 

Edit

Stupid to haven't tell it before. But, you can just check if the attribute exist if you want a boolean:

domNode.hasAttribute("data-draggable"); 
like image 145
Simon Boudrias Avatar answered Sep 30 '22 11:09

Simon Boudrias