User-defined HTML element attributes?

What I need to do is to store some data about the item.

For example, let's say I have an <li> list item , and I want to save some data about it in the item, for example, "This is item 1 of XYZ . "

The only way I know how to do this (which I don't want to do if I can avoid):

<li id='item1'>
  Item 1
  <!--This is element 1 from XYZ-->
</li>

<script>
  // read it something like this
  var e = document.getElementById('item1').innerHTML; 
  // then parse out the comment, etc.
  // --
</script>

I really want something like this (which I'm sure impossible):

// example
<li id='item1' userdata='This is element 1 from XYZ'>Item 1</li>

.. of course, I would like to have access to it somehow through javasscript.

Alternatively, is there any other way to achieve this?

Thanks -

+5
source share
7 answers

userdata = "" JavaScript. :

var theData = document.getElementById('item1').getAttribute('userdata');

HTML5, data- *, :

<li id='item1' data-foo='This is element 1 from XYZ'>Item 1</li>

- (.. , ). data- * :

var theData = document.getElementById('item1').data.foo;

, , .

( ), - :

var e = document.getElementById('item1');
var n = e.firstChild;
while (n && n.nodeType != Node.COMMENT_NODE) {
    n = n.nextSibling;
}
// now n.nodeValue will have the comment contents

( , IE .)

+13

HTML. , , , beheaviour - undefined. jQuery. data(), . , class, .

, ? , , / informatino. :

$("#item1").data({source: "Thsi is element 1 from XYZ"});
+5

, span .

<span class="data">.....</span>

, display:none, ...

DOM.

+1

setUserData() getUserData() http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#Node3-setUserData

:

<html>
<head>
    <script type="text/javascript">
        function set(){
            var a = document.getElementById("testElement");
            a.setUserData("testData", "Some text", null);
        }

        function get(){
            var a = document.getElementById("testElement");
            alert(a.getUserData("testData"));
        }
    </script>
</head>
<body>
    <span id="testElement"/>
    <form>
        <input type="button" value="setUserData" onclick="set()"/>
        <input type="button" value="getUserData" onclick="get()"/>
    </form>
</body>

+1

HTML- , , , Javascript, getAttribute.

0

innerText. style, , .

, . ?

0

// html, node?

.hiddendata{
 display: none
}

<li id= 'item1'> 
Item 1
<span class= "hiddendata"> This is element 1 from XYZ</span> 
</li> 

function readHiddenData(who){
 var A= [], n= who.firstChild;
 while(n){
  if(n.className= 'hiddendata'){
   A[A.length]= n.textContent || n.innerText || '';
  }
  n= n.nextSibling;
 }
 return A;
}

function showHiddenData(who){
 var n= who.firstChild;
 while(n){
  if(n.className= 'hiddendata'){
   n.style.display= "inline"
  }
  n= n.nextSibling;
 }
}
0

All Articles