How to add a new rule to an existing CSS class - javascript

In the code below i have illustrated what I am trying to achieve...
Altering an existing CSS class by adding a new rule to it.
<head>
<style>
h4.icontitle
{font-size: 22pt;}
</style>
</head>
<body>
<script type="text/javascript">
textpercent = 84;
document.styleSheets[1].cssRules.['h4.icontitle'].style.setProperty('-webkit-text-size-adjust', textpercent+'%', null);
</script>
<h4> hello </h4>
</body>
This is for a pre-process element of a site running on screens of different sizes.
The result will be...
h4.icontitle
{font-size: 22pt;
-webkit-text-size-adjust:84%;}
Which will be visible when inspecting the DOM.
Any ideas would be most welcome. Javascript only - no JQuery here...
SOLVED.
After a lot of trial and error, here is a working function that allows javascript to insert styles directly into the CSS
function changeCSS(typeAndClass, newRule, newValue)
{
var thisCSS=document.styleSheets[0]
var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules
for (i=0; i<ruleSearch.length; i++)
{
if(ruleSearch[i].selectorText==typeAndClass)
{
var target=ruleSearch[i]
break;
}
}
target.style[newRule] = newValue;
}
Called with
changeCSS("h4.icontitle","backgroundColor", "green");
Hopefully others will find this a useful method to use variables within their CSS in pure javascript.

This function works perfectly for my site.
function changeCSS(typeAndClass, newRule, newValue)
{
var thisCSS=document.styleSheets[0]
var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules
for (i=0; i<ruleSearch.length; i++)
{
if(ruleSearch[i].selectorText==typeAndClass)
{
var target=ruleSearch[i]
break;
}
}
target.style[newRule] = newValue;
}
Called with
changeCSS("h4.icontitle","backgroundColor", "green");

/**
Use this to update style tag contents
**/
var css = 'h1 { background: grey; }',
head = document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
To work with elements within body use querySelector to target elements upon their CSS identifier. This should help you
https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector
var el = document.querySelector(".icontitle");
el.setAttribute("style","-webkit-text-size-adjust:84%");
Or you can prepare a css snippet and use it conditionally ex: if "new_css" is the new change then
/**css code in style tag**/
.icontitle{
/**style at initial stage**/
}
.icontitle-new-modified{
/**modified css style at later stage**/
}
//after a condition is satisfied
el.setAttribute("class","icontitle-new-modified");

I put an example together that should suit your needs
DEMO jsFiddle
// this gets all h4 tags
var myList = document.getElementsByTagName("h4"); // get all p elements
// this loops through them until it finds one with the class 'icontitle' then it assigns the style to it
var i = 0;
while(i < myList.length) {
if(myList[i].className == "icontitle") {
myList[i].style.color="red";
}
i++;
}

Try this piece of code
$('h4.icontitle').css('-webkit-text-size-adjust','84%');

Related

Detect !important css rule of separate DOM element with JS

How could I detect !important rule of style property for directed DOM element?
ex:
<div class = "class">
***content***
</div>
.class{
top: 45px!important; 
}
let elmStyles = document.getElementsByClassName('class')[0].style;
/* i need this =====> */ let isImportant = elmStyles.getPropertyPriority("top");
I`ve found some info about that, but I can not apply it for concrete DOMelement
https://developer.mozilla.org/ru/docs/Web/API/CSSStyleDeclaration/getPropertyPriority
You can find all the elements to which top and that particular class which .class is applied to
Means you need to loop through all the rules and find the corresponding class for it
var declaration = document.styleSheets;
for(var i=0;i<declaration.length;i++) {
for(var j=0;j<declaration[i].cssRules.length;j++) {
var rule = declaration[i].cssRules[j];
if(rule.style.getPropertyPriority("top")=="important") {
var selector = rule.selectorText;
if(selector[0]==".") {
var elements = document.getElementsByClassName(selector.substring(1));
for(var k=0;k<elements.length;k++) {
var element = elements[k];
console.log(element)
}
}
}
}
}
this loop will loop through all rules and find top is marked as !important
Then select all elements to which the class is applied and print in the console
Currently I have written only for class, for ID and tag name this is code will not work

Modify previously defined style in JS

A function for creating style constructed as follows
function createStyle(css) {
var head = document.head || document.getElementsByTagName("head")[0];
var style = document.createElement("style");
style.type = "text/css";
if(style.styleSheet) {
style.styleSheet.cssText = css;
} else {
var textNode = document.createTextNode(css);
style.append(textNode);
}
head.append(style);
}
inspired by Christoph and TomFuertes code. Then it is called to create a style with class name tab
createStyle(`
.tab button {
background: inherit;
float: left;
outline: none;
border: none;
padding: 8px 6px;
width: 60px;
cursor: pointer;
}
`);
and a HTML element using the style
var div = document.createElement("div");
div.className = "tab";
parent.append(div);
is also created. So it all works.
After that I need to modify the style with class name tab, where following code
var style = document.getElementsByTagName("style");
var css = style[0].innerHTML
var className = css.split(" ")[0].split(".")[1];
is used to get the style class name. I have managed to get the style class name tab and also the string containing the object in css.
The question is how I modify the style without I modify the string and recreate the style? Or if I have to do that, how I should delete the previous defined style if there are already some styles which I have not recorded the order for accessing them through array sytle[].
Proposed solution
Using How to change/remove CSS classes definitions at runtime? suggested by Achu I made this function
// Change style attribute with value
function changeStyleAttribute(style, attr, value) {
var N = document.styleSheets.length;
var styles = document.styleSheets;
for(var i = 0; i < N; i++)
{
if(styles[i].rules[0].selectorText == style)
styles[i].rules[0].style[attr] = value;
}
}
which is called
changeStyleAttribute(".tab", "width", "299px");
and works. I hope there is another better and simpler solution.
You'll want to use document.styleSheets[i].cssRules which is an array you need to parse through to find the one you want, and then rule.style.setProperty('font-size','10px',null);
Refer to this link: How to change/remove CSS classes definitions at runtime?.
Hope this helps.

Hide DIV depending on text inside another DIV in DOM with javascript?

I need to hide a DIV depending on userroles. I have no variable to use from these userroles, except text inside a title tag.
html:
<title>admin</title>
If admin then hide the DIV for an example
<div class="demo"></div>.
I can only use Vanilla Javascript.
Update: This hides the div, but shows it for a blink at pageload:
$('document').ready(
function() {
function _title(){
if(document.title=="admin"){
document.getElementById('demo').style.display="none";
}
}
window.onload=_title;
});
Okay well this should answer your question.
This will set style none for element with the ID of demo.
function _title(){
if(document.title=="admin"||document.title=="admin1"){
document.getElementById('demo').style.display="block";
}
}
window.onload=_title;
If you to use class rather than id to allow this function to work with multiple elements....
function _title(){
if(document.title=="admin"){
var DemoClass = document.getElementsByClassName('demo');
for(var i=0; i<DemoClass.length; i++) {
DemoClass[i].style.display="block";
}
}
}
window.onload=_title;
If this answers your question, marking your question as answered would be appreciated.
Simple add this to your page
For id
<style type="text/css">
#demo{display:none;}
</style>
For class
<style type="text/css">
.demo{display:none;}
</style>
---- Titles that contain the word Admin ----
For Class
function _title(){
var allow = document.title.search("admin");
if(allow>-1){
//Set display for demo element
var DemoClass = document.getElementsByClassName('demo');
for(var i=0; i<DemoClass.length; i++) {
DemoClass[i].style.display="block";
}
}}
For id
function _title(){
var allow = document.title.search("admin");
if(allow>-1){
//Set display for demo element
document.getElementById('demo').style.display="block";
}}

How to get a style property from a css class and set it to another css class?

Is it somehow possible to get a style property from a css class that is not used anywhere?
I'd like to read for example the color property that I want to apply to an animation with jquery ui but I want to avoid duplicating them again in the js code.
Let's say I have this:
.default-style {
color: red;
}
.disabled-style {
color: gray;
}
.current-style {}
<span class="current-style">Hello world!</span>
Now I would like to set the .default-style color to the .current-style and then animate the color from the .default-style to the .disabled-style and back on click but I don't know how to get them without creating a hidden element.
var currentColor = ""; // I'm stuck here. Get color from css class?
$("span.abc").animate({ color: currentColor });
You can cheat by creating an element, applying the class, adding the element to the document, getting its color, then removing it. If this is all done in one code block, the user will never see the element:
var div = $("<div>").addClass("default-style").appendTo(document.body);
var color = div.css("color");
div.remove();
Alternately, you can loop through document.styleSheets in the document, and loop through the rules of each stylesheet looking for the one that uses that simple class selector, then look at the styles that rule defines.
Gratuitous snippet: ;-)
var div = $("<div>").addClass("default-style").appendTo(document.body);
var color = div.css("color");
div.remove();
$("<p>The color is: " + color + " (the color of this paragraph)</p>").css("color", color).appendTo(document.body);
.default-style {
color: red;
}
.disabled-style {
color: gray;
}
.current-style {}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="current-style">Hello world!</span>
Side note: jQuery's animate function doesn't animate colors natively, you need to add a plugin to do it (jQuery UI bundles one, but if you're not using jQuery UI, you can just use one of the plugins that does this, such as this one, directly).
Correct Way ! Without cheating the document
var currentColor;
var styleSheets = document.styleSheets;
for(var j=0; !currentColor && j<styleSheets.length; j++)
{
var styleSheet = styleSheets[j];
var cssprops = styleSheet.cssRules || styleSheet.rules; // .rules is for older IE
for (var i = 0; i < cssprops.length; i++) {
if(cssprops[i].selectorText == '.default-style');
currentColor = cssprops[i].style.getPropertyCSSValue('color').cssText;
}
}
$("span.abc").animate({ color: currentColor });
Reference From https://developer.mozilla.org/en-US/docs/Web/API/document.styleSheets

Styling a div's links in Javascript [duplicate]

This question already has answers here:
Setting CSS pseudo-class rules from JavaScript
(12 answers)
Closed 9 years ago.
I would like to change the style of an element's links using JavaScript. The CSS would look like:
#element a:link {
color: #000;
}
I know that you can change the style of the the element itself, as in:
elementObject.style.color = '#000';
Pseudo-code for what I want would be:
|
V
elementObject.[A:LINK].style.color = "#ff0000";
How can I do this?
the :link :visited are not true CSS elements, but part of the CSS rule, this means you need to edit the rule, change the rule or apply another class...
var css='#element a:link { color: #ff0000 }';
style=document.createElement('style');
if (style.styleSheet)
style.styleSheet.cssText=css;
else
style.appendChild(document.createTextNode(css));
document.getElementsByTagName('head')[0].appendChild(style);
You can loop through links and set the one by one.
<script type='text/javascript'>
function new_window()
{
var anchors = document.getElementsByTagName('a');
for(var i = 0; i < anchors.length; i++)
{
anchors[i].style.color = '#000';
}
}
window.onload = new_window;
</script>
The other way to create a wrapper div with the "wrapper" class name. Then replace its class name to "wrapper2" with JavaScript. After then the rules in the CSS like .wrapper a will be activated.
.wrapper a
{
//normal code
}
.wrapper2 a
{
color: #000;
}
select visited links is javascript isnt possible merely by a selector. have a look at Detect Visited Link In Chrome
and this http://archive.plugins.jquery.com/project/Visited
so if you wanna set the style of a visited/unvisited link using javascript loop through all the links in the body. checking wether they are visited and then apply style.
var as = document.getElementsByTagName('a');
for(var i=0;i<as.length;i++){
//check and set the style here
}
function addCss(sel, css){
S= document.styleSheets[document.styleSheets.length-1];
var r= (S.cssRules!= undefined)? S.cssRules: S.rules;
if(S.insertRule) S.insertRule(sel+'{'+css+'}',r.length);
else if(S.addRule)S.addRule(sel,css,r.length);
}
addCss('button:hover','background-color:blue;');

Categories