|
| 1 | +<style> |
| 2 | +#test { |
| 3 | + padding: 10px; |
| 4 | + border: 1px solid #ccc; |
| 5 | + margin: 20px 0; |
| 6 | +} |
| 7 | +pre { |
| 8 | + overflow-x: auto; |
| 9 | + padding: 10px; |
| 10 | + border: 1px dashed #ccc; |
| 11 | + background: #fff; |
| 12 | + font-size: 12px; |
| 13 | +} |
| 14 | +</style> |
| 15 | +<title>data-*</title> |
| 16 | +<article> |
| 17 | + <section> |
| 18 | + <p>The <code>data-[name]</code> attribute on elements can now be accessed directly via the DOM using <code>element.dataset.[attr]</code>.</p> |
| 19 | + <p>Try openning the Web Console and editing <code>element.dataset</code> directly: <br /><code>element.dataset.foo = 'bar';</code></p> |
| 20 | + </section> |
| 21 | + <p id="status">Not connected</p> |
| 22 | + <section> |
| 23 | + <div id="test" data-name="rem" data-height="short">This element has data</div> |
| 24 | + <input type="button" value="Show data" id="show" /> |
| 25 | + <input type="button" value="Change data via dataset" id="change1" /> |
| 26 | + <input type="button" value="change data via setAttribute" id="change2" /> |
| 27 | + </section> |
| 28 | + <pre><code id="element">[click buttons above to show element html]</code></pre> |
| 29 | +</article> |
| 30 | +<script> |
| 31 | +(function () { |
| 32 | + |
| 33 | +function show() { |
| 34 | + code.innerHTML = test.outerHTML.replace(/[<>]/g, function (m) { |
| 35 | + return { '<': '<', '>': '>' }[m]; |
| 36 | + }); |
| 37 | + |
| 38 | + for (var prop in test.dataset) { |
| 39 | + code.innerHTML += '\nel.dataset.' + prop + ' = "' + test.dataset[prop] + '"'; |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +var state = document.getElementById('status'), |
| 44 | + code = document.getElementById('element'); |
| 45 | + |
| 46 | +var test = window.element = document.getElementById('test'); |
| 47 | + |
| 48 | +if (test.dataset === undefined) { |
| 49 | + state.innerHTML = 'dataset not supported'; |
| 50 | + state.className = 'fail'; |
| 51 | +} else { |
| 52 | + state.className = 'success'; |
| 53 | + state.innerHTML = 'element.dataset supported'; |
| 54 | +} |
| 55 | + |
| 56 | +addEvent(document.getElementById('show'), 'click', function () { |
| 57 | + show(); |
| 58 | +}); |
| 59 | + |
| 60 | +addEvent(document.getElementById('change1'), 'click', function () { |
| 61 | + test.dataset.name = 'via el.dataset'; |
| 62 | + show(); |
| 63 | +}); |
| 64 | + |
| 65 | +addEvent(document.getElementById('change2'), 'click', function () { |
| 66 | + test.setAttribute('data-name', 'via setAttribute'); |
| 67 | + show(); |
| 68 | +}); |
| 69 | + |
| 70 | + |
| 71 | +})(); |
| 72 | +</script> |
0 commit comments