-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
63 lines (54 loc) · 1.64 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
module.exports = microdata
var lookup = { '*' :'textContent'
, meta :'content'
, audio :'src'
, embed :'src'
, iframe :'src'
, img :'src'
, source :'src'
, video :'src'
, a :'href'
, area :'href'
, link :'href'
, object :'data'
, time :'datetime'
}
var query = require('component-query').all
function microdata(itemtype, scope) {
scope = scope || document.documentElement
var elems = query('[itemscope][itemtype="' + itemtype + '"]', scope)
, arr = []
for (var i = 0, len = elems.length; i < len; i++) arr.push(extract(elems[i]))
return arr
}
microdata.extract = extract
function extract(scope) {
var obj = { _type: scope.getAttribute('itemtype') }
, elems = [].slice.call(scope.children)
, elem
, key
/*jshint boss:true*/
while (elem = elems.shift()) {
if (key = elem.getAttribute('itemprop')) add(obj, key, value(elem))
if (elem.getAttribute('itemscope') === null) prepend(elems, elem.children)
}
return obj
}
function add(obj, key, val) {
/*jshint eqnull:true*/
if (val == null) return
var prop = obj[key]
if (prop == null)
obj[key] = val
else
if (prop instanceof Array) prop.push(val)
else obj[key] = [prop, val]
}
function value(elem) {
if (elem.getAttribute('itemscope') !== null) return extract(elem)
var attr = lookup[elem.tagName.toLowerCase()] || lookup['*']
return elem[attr] || elem.getAttribute(attr)
}
function prepend(target, addition) {
[].unshift.apply(target, [].slice.call(addition))
}