Invalid argument error when trying to get the value of an attribute with getAttribute in Internet Explorer <= 7

back to ajnasz.hu

About the issue

If use some custom attribute in your HTML page, which name contains a :, and you want to try to get its value with getAttrite method, you will get an error message if you try to do this on a table element, which doesn't has the attribute. It does not happens with every element only with tables (or maybe with others but I found only this one yet).

I know, that it's not valid to use custom attributes like this, but why we get the error only for tables? Otherwise the page has the XHTML 1.0 Strict doctype.

Click on the buttons in IE7 or older to try!

Table1
Ingyom Bingyom Malibe
Foo Bar Baz
Table2
Ingyom Bingyom Malibe
Foo Bar Baz

Lorem ipsum dolor

Javscript Code


var getXFooBar = function(elementID) {
  var results = document.getElementById('result');
  var element = document.getElementById(elementID);
  if(!element || !results) return;
  results.style.display = '';
  results.innerHTML = '';
  var fooBar = null;
  try { // It will happen if you are using IE7 and the element is a table
    fooBar = element.getAttribute('x:foo-bar');
  } catch(e) {
    results.innerHTML += 'fakk, what the hell?<br />message: ' + e.message + '<br />';
  }
  results.innerHTML += fooBar ? '"' + elementID + '" element\'s value is ' + fooBar : 'No foobar for element ' + elementID;
  results.style.display = 'block';
  element.className = 'hi';
  setTimeout(function(){element.className = '';}, 2000);
};
    

HTML Code


<div id="result"></div>
<table id="table-1" x:foo-bar="Foo Bar">
  <caption>Table1</caption>
  <thead>
    <tr>
      <th>Ingyom</td>
      <td>Bingyom</td>
      <td>Malibe</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Foo</td>
      <td>Bar</td>
      <td>Baz</td>
    </tr>
  </tbody>
</table>
<button onclick="getXFooBar('table-1')">Get Foo Bar Value for table1</button>
<table id="table-2">
  <caption>Table2</caption>
  <thead>
    <tr>
      <th>Ingyom</td>
      <td>Bingyom</td>
      <td>Malibe</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Foo</td>
      <td>Bar</td>
      <td>Baz</td>
    </tr>
  </tbody>
</table>
<button onclick="getXFooBar('table-2')">Get Foo Bar Value for table2</button>
<div id="just-div">Lorem ipsum dolor</div>
<button onclick="getXFooBar('just-div')">Get Foo Bar Value for a div</button>