Native JS for reading custom HTML5 data attributes

I learned that HTML5 includes a tool for setting custom attributes on elements using a data prefix. However, I'm a bit confused about how to read properties during a javascript code block. I think this is my interpretation of how DOMStringMap works.

Can anyone simplify reading the properties of the following html sample.

<span data-complex-key="howtoRead" data-id="anId">inner</span> 

Trying to follow does not work as expected

 spanEl.dataset['id'] // straight-forward and result is anId spanEl.dataset['complex-key'] // undefined spanEl.dataset['complex']['key'] // throws 'cannot read property of undefined' spanEl.getAttribute('complex-key') // there a null however, spanEl.getAttribute('data-complex-key') // this variant seems to work 

Another thing that makes me wonder is that the CSS selector seems to follow the same pattern I wrote in the DOM, so why is this not the case when you read javascript.

For example, this will match

  span[data-complex-key="howtoRead"] { color:green } 

Appreciate help still more exposed with canvas, video, and HTML5 local storage :)

+4
source share
4 answers

In vanilla-JS, assuming spanEl is a reference to a DOM node

 spanEl.dataset['complexKey'] 

will work using camelCase notation (see http://jsbin.com/oduguw/3/edit ) when your data attribute contains hypens ( - ) as well

 spanEl.getAttribute('data-complex-key') 

will work fine, as you already noticed. As a side note, in jQuery you can access this data attribute with

 $(spanEl).data("complex-key") 
+8
source

In Chrome, it seems that the data card is not so simple:

 console.log(spanEl.dataset);​​​​​​​​​​​​​​ //shows: //DOMStringMap // complexKey: "howtoRead" // id: "anId" 

It converts the "complex key" to "complexKey".

Although not so simple, this behavior is defined in the HTML5 specification:

http://dev.w3.org/html5/spec//global-attributes.html#dom-dataset

+2
source

Your first and last method is correct if you are not using any libraries. However, the minus key is converted to Case Camel, so the complex key becomes complexKey:

 spanEl.dataset['id'] spanEl.dataset['complexKey'] spanEl.getAttribute('data-complex-key') 

However, only the latter works in IE until 9. (I don’t know about 10.) Data attributes are nothing more than ordinary attributes that have a naming convention in this case.

+1
source
  spanEl.dataSet["complexKey"] 

// Using jQuery, you can try this

  $('span').data('complex-key') // Will give you **howtoRead** $('span').data('id') // Will give you **anId** 
0
source

Source: https://habr.com/ru/post/1436422/


All Articles