Custom data in XHTML 1.0 Strict
Asked Answered
L

6

7

I use some custom attributes in my html, for jquery stuff. I saw there are data-XYZ attributes in HTML5, but I need to be xhtml 1.0 strict. What other options do I have?

Lavish answered 15/11, 2010 at 21:36 Comment(2)
+1 for an interesting question. I'm curious as to the reason for the down-vote...Schramm
@David Thomas, you and me both :)Lavish
C
5

You can use the jQuery MetaData plugin which allows you to write data in the class attribute in JSON format:

<li class="someclass {some: 'data'} anotherclass">...</li>

Then in your jQuery, to get at the data:

var data = $('li.someclass').metadata();
if ( data.some && data.some == 'data' )
    alert('It Worked!');

This should meet your requirements of being xhtml 1.0 strict, and also allows you to use a plug-and-play solution :)

Collative answered 23/11, 2010 at 9:31 Comment(4)
It works as intended, but I need to be able to select via jquery selectors on the custom data. For ex. I had <div data1="val1">, then I did $('div[data1=val1]'); now I have <div class="{data1: 'val1'}">, how do I select the same thing?..Lavish
You could do it like so: <div class="data1 {data: 'val1'}">, and select it by doing var myVal = $('div.data1').metadata().data; which makes myVal = 'val1'. To get the same effect as $('div[data1=val1]'), you would have to manually loop over all elements which match $('div.data1'), which is the same as what jQuery does internally anyway, so shouldn't be any slower.Collative
According with XHTML Schemas: w3.org/TR/xhtml1-schema/#xhtml1-strict the value space of class is defined as <xs:attribute name="class" type="xs:NMTOKENS"/> and, unfortunately, {some: is not a valid NMTOKEN so I'm having problems with this solution :(Gwennie
I kindly suggest to reject this answer as the valid in favor of my solution explained below for two reasons: (1) the proposed solution is not XHTML valid and (2) the jQuery MetaData plugin is no longer available (maybe because of 1). Thanks!Gwennie
P
1

You have a couple of options that spring to mind.

Assuming you want site-specific custom attributes for use with scripting, one way is to embed a script right with the element you want to add attributes to. For example:

  <span id="myId1"><script type="text/javascript">
      var myId1Span = document.getElementById("myId1");
      myId1Span.myData = {};
      myId1Span.myData.firstname = "John";
      myId1Span.myData.surname = "Smith";
  </script>My Text</span>

Another way of adding extra data to your elements is to embed the data in the class attribute.

So you could have

<span class="myCssClass http://example.com/hasData 
                data-firstname:John data-surname:Smith">My Text</span>

If you're using the data for scripting, then you can add the script below to extract this data. You can add this just before the close body tag.

  <script type="text/javascript">
      //<![CDATA[
      if (! document.getElementsByClassName)
      {
        // From http://lawrence.ecorp.net/inet/samples/js-getelementsbyclassname.shtml
        document.getElementsByClassName = function(class_name)
        {
          var docList = this.all || this.getElementsByTagName('*');
          var matchArray = new Array();

          var re = new RegExp("(?:^|\\s)"+class_name+"(?:\\s|$)");
          for (var i = 0; i < docList.length; i++)
          {
            if (re.test(docList[i].className) )
            {
              matchArray[matchArray.length] = docList[i];
            }
          }
          return matchArray;
        }
      }

      var hasData = document.getElementsByClassName("http://example.com/hasData");
      for (var i = 0 ; i < hasData.length ; i++)
      {
        var myElem = hasData[i];
        myElem.myData = {};
        var dataClassList = myElem.className.split(" ");
        for (var j = 0 ; j < dataClassList.length ; j++)
        {
          var dataCandidate = dataClassList[j];
          if (dataCandidate.substring(0, 5) == "data-")
            if (dataCandidate.indexOf(":") >= 0)
            { 
              var nameValue = dataCandidate.split(":", 2);
              myElem.myData[nameValue[0].substring(5)] = nameValue[1];
            }
        }
      }
      //]]>
  </script>

This should result in the same myData object being added to the span as the first option.

The http://example.com/hasData class is just a flag to indicate which elements should be processed. You can use any string you like for this purpose.


Both methods are XHTML 1.0 Strict compliant and will work when served either as text/html or application/xhtml+xml

Peddler answered 21/11, 2010 at 12:56 Comment(2)
This is the kind of answer I'm looking for. BTW, I'm using jQuery, which can store data in elements using $(..).data(x, y), do you know if there's a way of getting data readable by jQuery, directly into the html? (maybe some plugin that uses your class solution, something like that..)Lavish
I'm not aware of a jQuery plug-in of this nature, but then I don't use jQuery very often. Maybe others will be able to help.Peddler
M
0

I just want to know if the strict spec allows for some way of adding extra data to elements.

No.

(Should you care? Probably not, but that's your call.)

Marieann answered 20/11, 2010 at 21:13 Comment(0)
G
0

Here is a proposed solution that is valid XHTML 1.0

<li class="someclass someData anotherclass">...</li>

combined with

<style>
someData {
  --custom-some: data
}
</style>

Or use the style attribute directly on the element.

Note 1: The syntax of the class attribute does not allows json metadata. The open curly bracket is not valid NMToken. Note 2: The attribute name in the metadata is preceded with --custom- in order to avoid validation issues of the content of the CSS itself

Gwennie answered 24/8, 2020 at 16:39 Comment(0)
S
-2

The way I look at it, I don't really care if it's valid per the XHTML spec if I am serving it as text/html because it won't be real xhtml anyway. This is the case in 99% of uses of xhtml.

As long as you don't have critical errors such as missing end tags and such, you don't necessarily have to worry about what the validator tells you as long as you are aware why. The XHTML 1.0 spec was written years ago. Technology moves fast. You'll never be able to use new features if you restrict yourself to make your site "valid" at the time of the spec writing.

Though my real suggestion would be to just switch to HTML 5 - the xhtml syntax AFAIK is compatible with HTML 5. There may be some minor inconsistencies but for the most part it should be a fairly straight-forward transition.

Synecology answered 15/11, 2010 at 21:41 Comment(7)
I know all this. I just want to know if the strict spec allows for some way of adding extra data to elements.Lavish
Don't think so per #2413647 - unless you make your own DTD.Synecology
Making your own DTD stops it being XHTML though.Depoliti
I develop ecommerce sites using the latest technolology. 100% valid. Works in all browsers. HTML was created before XHTML so, by the above statement, we don't need to pay much attention to that either. I thought such talk went out of style in 2001 or so.Cutup
@Cutup - is your CSS 100% valid? Do you use any CSS3 features? Do you use any vendor-specific css properties? Do you really use the "latest" technologies? Would be great if you linked to one of your e-commerce sites so I can observe.Synecology
@meder - vendor specific extensions are part of the CSS spec and, therefore, valid, despite the error from the validator. However, ignoring errors from the validator, as you suggest, is horrible advise.Cutup
@Cutup - still waiting for your example of an e-commerce site with the latest techniques that's 100% valid and consistent in all browsers. Also, in general I advise that people strive for 100% validation but there will be times when you can not get 100% validation, instances such as vendor-specific extensions which will cause errors, which you can ignore, or at least be aware of the reason why the error is present from the validator.Synecology
B
-2

If you want proper proper XHTML, you need to use the HTML5 doctype (<!doctype html>). Then you can use the data- attributes.

<element data-usage='for an example' data-number='28' />

This is perfectly valid XHTML strict (I use this on my website). The purpose for this is so that the W3C doesn't come along and create an attribute with the same name as one you have been using on your website and break it.

To get the value in JavaScript, you need to use elem.getAttribute('data-name');. The W3M spec does include using ele.dataset.name but this is not supported by a wide varity of browsers yet.

Binder answered 25/11, 2010 at 23:58 Comment(1)
But HTML5 is not XHTML. HTML5 isn't even valid XML necessarily. Which version of XHTML do you mean? How is that valid? To quote the w3 validator: "there is no attribute "data-usage"" (checked as XHTML 1.1).Prithee

© 2022 - 2024 — McMap. All rights reserved.