Commit 312c20c9 authored by S Anand's avatar S Anand

ENH: add G.style('selector') that returns CSS stylesheet rules matching selector

parent 5a0750fa
......@@ -5,6 +5,7 @@ G_JS= lib/canvas-to-blob.js \
lib/start.js \
lib/url.js \
lib/csv.js \
lib/style.js \
lib/download.js \
lib/wrap.js \
lib/zoom.js \
......
// Return all CSS rules matching a selector.
// e.g. G.style(/^\.item$/i) returns all rules matching '.item'
// e.g. G.style('.item') returns all rules exactly matching '.item'
G.style = function(selector) {
var stylesheets = global.document.styleSheets,
matches = [],
string_selector = typeof selector == 'string'
for (var i=0, stylesheet; stylesheet=stylesheets[i]; i++)
for (var j=0, rule; rule=stylesheet.cssRules[j]; j++) {
var text = rule.selectorText
if (text && (string_selector ? text == selector : text.match(selector)))
matches.push(rule)
}
return matches
}
......@@ -29,6 +29,7 @@
<script src="network.js"></script>
<script src="csv.js"></script>
<script src="url.js"></script>
<script src="style.js"></script>
<script src="svgdom.js"></script>
<script src="aspect.js"></script>
<script src="dispatch.js"></script>
......
describe('G.style', function() {
it('finds CSS rules as strings', function() {
$('<style>.root {} .root h1 {}</style>').appendTo('head')
var result = G.style('.root')
assert.equal(result.length, 1, 'Only 1 rule matching .root')
var result = G.style(/^\.root/i)
assert.ok(result.length > 1, 'Multiple rules start with .root')
for (var i=0, selector; selector=result[i]; i++)
assert.ok(selector.selectorText.match(/^\.root/i), 'All matching rules start with .root')
$('<link id="styleTest" rel="stylesheet" type="text/css" href="style.test.css">')
.on('load', function() {
var result = G.style('#id')
assert.equal(result.length, 1, 'Only 1 rule matching #id')
assert.equal(result[0].selectorText, '#id', 'Rule matches #id')
var result = G.style(/^#id/i)
assert.ok(result.length > 1, 'Multiple rules start with #id')
for (var i=0, selector; selector=result[i]; i++)
assert.ok(selector.selectorText.match(/^#id/i), 'All matching rules start with #id')
$('#styleTest').remove()
})
.appendTo('head')
});
})
/* When searching for #id, there's only one exact match, but multiple partial matches */
#id { }
#id h1 {}
#id h2 {}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment