I’m working in the latest version of Opera. It supports the Microdata API, but when I typed the following code, it does not work.
<head>
<script type="text/javascript">
var user = document.getItems('http://schema.org/Person')[0];
alert('Hi there ' + user.properties['name'][0].textContent + '!');
function supports_microdata_api() {
return !!document.getItems;
}
alert(supports_microdata_api());
</script>
</head>
<body>
<div itemscope itemtype="http://schema.org/Person">
<span itemprop="name">Fatima Zohra</span>
<img src="" itemprop="image" />
</div>
Can anyone tell me what I’m doing wrong?
You need to wait until the page loads; you’re calling for something:
That’s not part of the DOM yet; your code is run before the DOM is aware of the “yet unseen” element.
Use
window.onloadto wait for the pageonloadevent to fire, which occurs after the elements have been parsed.http://jsfiddle.net/eY63s/2/
Or, alternately, put the code after the DOM elements in page order.
A more modern method is to use event delegation:
http://jsfiddle.net/eY63s/3/
Although at least earlier versions of IE support
element.attachEventinstead, IE9 or later browsers do/will supportelement.addEventListener.And this is a safer way to check and call the methods:
http://jsfiddle.net/eY63s/4/
Note the use of
var userinside the anonymous function, which creates a closure and preventsuserfrom escaping to the global scope. This is a “better” way of handling variables, which can help prevent them from being overwritten by accident due to global sharing. On the other hand, you will not be able to calluserfrom outside that scope. Resist the urge to push it to the global scope, though, which can be easier but is a bad habit and prone to at times difficult to find errors.