How can I access CSS selectors programmatically? [closed]
Tags: javascript,css
Problem :
I'm working from an example I found on the web to create supposed HTML5 tooltips in CSS3.
.tooltip {
border-bottom: 1px dotted #333;
position: relative; cursor: pointer;
}
.tooltip:hover:after {
content: attr(title);
position: absolute;
white-space: nowrap;
background: rgba(0, 0, 0, 0.85);
padding: 3px 7px;
color: #FFF;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
margin-left: 7px;
margin-top: -3px;
}
How can I create this programmatically as the application purposely contains no HTML or CSS?
From what I can tell so far, I think the 'after' is a CSS selector but I cannot find out any more information as to how I can create, access or modify this in the DOM using JavaScript.
JavaScript solutions only please, thank you.
Solution :
You can add any CSS rule in the document using insertRule
. On MDNs page, there's a method which shows a cross-browser compatible method to insert arbitrary CSS rules.
Since your app does not contain any HTML, you have to create a <style>
object yourself using document.createElement
. document.styleSheets[0].cssRules
will be null
when the style sheet is from a different origin.