Understanding Name Settings for Custom Data Attributes

Asked 1 months ago, Updated 1 months ago, 2 views

It's a simple question, but it doesn't work, so I'd like to ask you a question.

For example
When the height of the window is 1000px

<div data-1000="a">

When the height of the window is 500px

<div data-500="a">

As mentioned above, I want to give the name of the custom data attribute in HTML the window height, but it doesn't work.
Thank you for your understanding.

javascript

2022-09-30 11:24

1 Answers

There are many unclear parts, but
It's like this.

var height=window.innerHeight;
var theDiv = document.getElementById("it");

// When using setAttribute
varatt_name = "data-" + height;
theDiv.setAttribute(att_name, "a");
console.log(theDiv.getAttribute(att_name)));
console.log (theDiv.outerHTML);
theDiv.removeAttribute(att_name); // Delete
console.log (theDiv.outerHTML);

// For dataset IDL attribute
var name = "h" + height; // Names that begin with a number are not allowed.
theDiv.dataset [name] = "a";
console.log (theDiv.dataset [name]);
console.log (theDiv.outerHTML);
<divid="it">...</div>

Browse: Proprietary Data Attributes

Note:
It was pointed out that the attribute name can be a name that starts with a number for the characters that can be used, so
I looked it up again.

A proprietary data attribute is an attribute that does not belong to the namespace, whose name begins with the string ddata- " followed by at least one character.This is
XML compatible and does not contain ASCII uppercase characters.

Original Text :

.2.5.9 Embedded custom non-visible data with the data-* attributes

Custom data attribute is an attribute in no name space where name
starts with the string "data-", has at least one character after the
hyphen, is XML-compatible, and contains no uppercase ASCII letters.

XML-compatible (XML-compatible) name

Attribute names are said to be XML-compatible if they match the Name
production defined in XML, they contain no":"(U+003A) characters,
and their first three characters are not an ASCII case-insensitive
match for the string "xml".[XML]

Here's what I'm going to say
Name:

NameStartChar::=":"|[A-Z]|"_"|[a-z]|[#xC0-#xD6]|[#xD8-#xF6]|[#xD8-#x2FF]|[#x370-#x37D]|[#x370-#x1FFF]|[#x200C-#x200D]|[#x20-#xF2xF2]|xF2xF00]|xF#xF2xF#xF2|
NameChar::=NameStartChar|"-"|."|[0-9]|#xB7|[#x0300-#x036F]|[#x203F-#x2040]
Name::=NameStartChar(NameChar)*

"From now on, ""name"" must not start with a number; it must not start with xml; it cannot start with a colon (:) or a symbol.
This site is easy to understand.

Therefore, I think it means that names that start with numbers cannot be used according to the standard.
The one that works with a number (tried Chrome) is
I think it's probably because it's a valid attribute name for html5 including data (so it's OK to use setAttribute), but it's better not to use it.


2022-09-30 11:24

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.