This question already has answers here:
Are empty HTML data attributes valid?
(4 answers)
Closed 8 years ago.
Can you use data-* attributes as boolean attributes? If not, is there an alternative?
For example, you can have
<input disabled>
It would be helpful in some cases to have
<input data-on>
Using data-on="true" or data-on="" is not desirable -- the presence of the attribute should indicate its boolean value.
You can indeed use data-* attributes as if they were boolean attributes - however, as far as dataset is concerned <input data-on> is equivalent of <input data-on="">. This means that unlike required or other boolean attributes you won't be able to do this:
<input class="some-class" data-on required>
var elementOfInterest = document.querySelector(".some-class");
if (elementOfInterest.dataset.on) {
// We will never get here because dataset.on === ""
// and "" == false
}
if (elementOfInterest.required) {
// We *do* get here because required is a boolean attribute
}
Instead you'll need to do an explicit check against undefined:
if (elementOfInterest.dataset.on !== undefined) {
// We will get here because "" !== undefined
}
This gives you no way of distinguishing between data-on and data-on="", but if you are treating it as a boolean attribute, they both add up to the same thing anyway (only the absence of the attribute indicates falsity.)
Yes, data-* attributes can function as boolean attributes, at least as far as the DOM and browser selector engines are concerned: http://jsfiddle.net/MhJNb/
I haven't tested compatibility, but Chrome has no problem with applying div[data-on] rules to <div data-on></div>.
Related
I'm trying to generate nodes like this:
<div layout horizontal></div>
using DOM API.
I'm trying something like this:
var d = document.createElement("div");
d.setAttribute(...);
but never really managed to generate what I want. Any ideas how to do this?
Thanks.
The subject of your question reflects the basic confusion here. There is no such things as a "valueless attribute". There is merely a syntactic convenience available in HTML to write an attribute with no specific value, in cases where the mere presence of the attribute means something, whatever its value.
So you could write <input required> or <input required='true'> or <input required='false'> or <input required='notrequired'> and it would mean exactly the same thing (which is that input is required).
When you try to "print", in your words, the "valueless" attribute, whoever is responsible for the "printing" may choose to "be nice to you" and represent the attribute with no value, rather than showing the empty string. However, this does not change the fact that the attribute does have a value of the empty string, as can be seen easily by taking elt.getAttribute and examining the attribute value directly.
For instance, if I create a new div, then set its inner HTML to <input required="">, then certain environments, such as Chrome devtools, will show the element as <input required> rather than <input required="">. It's just syntactic sugar on both the way in and the way out, in other words.
Once I've created an element with a "valueless" attribute, which is actually an empty string, perhaps I can then make it truly valueless by setting the attribute value to null? Nope. elt.setAttribute('required', null) merely sets the attribute value to the string "null". Same for undefined.
Note that the DOM specification specifies an attribute of specified on Attr objects. However, as far as I can tell, this does not seem to be used, in the sense that, an attribute created by document.createAttribute always gets specified set to true, an attribute created by parsing HTML as in x.innerHTML = '<input required>'; always gets specified set to true, etc. And specified is marked readonly, so there's no way to examine what the effects of setting it to false would be anyway.
Anyway, what is your objective here? Why do you think you need to do this?
Just set an attribute to the empty string.
element.setAttribute('hidden', '')
You are looking for the createAttribute() and setAttributeNode() methods.
var elelement = document.createElement('div'),
var attribute = document.createAttribute('layout');
var attribute2 = document.createAttribute('horizontal');
element.setAttributeNode(attribute);
element.setAttributeNode(attribute2);
You can use setAttributeNode method of the element to append attribute node created with createAttribute:
var el = document.createElement('div'),
attr = document.createAttribute('layout');
el.setAttributeNode(attr);
For some reason IE9 returns "text" when writing the following code
Any ideas why. Other browsers return email
HTML
<input type="email">
javascript
alert($(input).attr('type'))
That is because IE9 does not support email, thus it ignores the values and resets it to the default value it supports... text.
For some reason IE9 returns "text" when writing the following code Any
ideas why. Other browsers return email
HTML
In a browser that is conformant with W3C standards (where element is a reference to the input element), then:
// Get the value of the HTML type attribute
element.getAttribute('type') // email
// Get the value of the DOM type property
element.type // email or text, depending on whether
// type email is supported or not
getAttribute returns the literal value of the associated attribute. The DOM property returns the actual value that the DOM property is set to (they may be, and often are, different values). IE 9 conforms to the standard—it doesn't support email so the DOM property returns "text", while getAttribute returns "email".
javascript
alert($(input).attr('type')) // email in jQuery version 1.6 and higher
alert($(input).prop('type')) // text in jQuery version 1.6 and higher
According to jQuery documentation, the attr method returns the attribute value, and it does in version 1.6 and higher. To get the DOM property, use prop. Prior to that, jQuery authors tried to second guess what developers actually wanted and attr returned either the attribute or DOM property value based on some unexplained logic.
I have used
element.hasAttribute('id')
in my code to test whether the element has an attribute id. But hasAttribute API is only compatible with browsers after IE8.Is there a similar API or technique which I can use to check the availability of an attribute for an element in my case "id".
In the absence of the hasAttribute method, you need to use getAttribute. This should return null if there is no attribute set, and an empty string otherwise. In practice, some browsers return an empty string, so there's no way in these browsers of telling whether it is an empty attribute or no attribute at all.
if ((element.getAttribute('id') === null) || (element.getAttribute('id') === '')) {
Just check element.id - it'll be an empty string if it's not set.
There's no need to use element.hasAttribute for those attributes that are mirrored by JS object properties.
This question already has answers here:
Are empty HTML data attributes valid?
(4 answers)
Closed 7 years ago.
I am wondering if html data attributes actually need a value to be applied?
I wonder this because often all we want to know is if the attribute is actually set to act as a flag. (sure we could use a class for this; but realistically unless you are going to style these items differently then the flags are more data than a semantic item).
A perfect example of this is if we want a link to scroll to it's target instead of jumping our jQuery code might look like:
$(document).on('click', '[data-scroll-link'], function(){/**do scroll**/});
I know in google chrome it is sufficient for the anchor to appear as
<a href="#bottom" data-scroll-link>Scroll to bottom</a>
But will that work everywhere? and is it even valid HTML5 (I believe it is due to the autofocus, autoplay etc attributes). or do we need:
Scroll to bottom
No. But...
As is common with all attributes, in the application/xhtml+xml serialisation, XML rules apply and the attribute must have an explicit name and (quoted) value.
So this question is really about the text/html serialisation, and therefore the relevant part of the HTML5 spec is Section 8 The HTML syntax
In particular, under attributes, it says:
Attributes can be specified in four different ways:
where the first of these is:
Empty attribute syntax
Just the attribute name. The value is implicitly the empty string.
It's necessary to understand though that the value is of string type, not of boolean type.
For example, with <input id="cb" type="checkbox" checked>, the "checked" attribute is reflected by a property that is either true or false. So
if (document.getElementById("cb").checked)
will evaluate to true for the above markup.
In contrast, with <input id="cb" type="checkbox" data-checked>, the "data-checked" attribute is reflected via the dataset object as a string. The value of this property is the empty string, which in JavaScript is falsey. So,
if (document.getElementById("cb").dataset.checked)
will evaluate to false for the above markup.
To do the equivalent test, compare the value for "not undefined". I.e.
if (document.getElementById("cb").dataset.checked !== undefined)
will evaluate to true for the above markup.
See http://jsfiddle.net/GAxvW/
Simple Boolean Test For Element Attributes
To expand on Alohci's excellent answer, the following is a simple, flexible way to test for a true boolean attribute value supplied using one of three standard HTML conventions: <foo data-bar/>, <foo data-bar="true"/>, or <foo data-bar="data-bar"/>.
var a = elem['data-bar'];
var aTrue = ( a != null && a !== false && a !== 0 && a.charAt(0) != 'f' &&
a.charAt(0) != 'n' );
With the code above, the value is false if undefined or set to one of: f*, n*, 0 (case-insensitive), and true if defined and set to one of: (empty string), (attribute name), (anything else).
Empty strings are evaluated to true here because HTML attributes without values are '' which equal false in JS (and something like <foo disabled/> should equal <foo disabled="true"/>). You can use the above code for more general string testing by removing != null && a !== false.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When to use setAttribute vs .attribute= in JavaScript?
Why do you sometimes set an attribute like this:
x.type = "submit";
and other times like this:
x.setAttribute("type", "submit");
I always figured it didn't matter which way, but I'm having an issue doing this:
x.onClick = save;
but when I switch it to this it works:
x.setAttribute("onClick", "save()");
setAttribute only works on DOM elements and lowercases the attribute name on HTML elements. And you can't use dot notation to assign values to dynamic attribute names.
And there's also this:
Using setAttribute() to modify certain attributes, most notably value
in XUL, works inconsistently, as the attribute specifies the default
value. To access or modify the current values, you should use the
properties. For example, use elt.value instead of
elt.setAttribute('value', val).