Can we change the value of attribute css by js - javascript

Can we you change the value of attribute CSS class by javascript?
I mean, that I had create
<li class="Item">first</li>
Where in CSS class I have attribute height: 200; width: 200;
And the question is anyhow can I change value in class of height && width by using javascript?

Yes, you can directly access CSS properties in the stylesheet, and support for this is improving, and actually looks pretty good today (scroll down to browser compatibility section).
This will, however, not be a straight-forward process since, with a large stylesheet, you'll either have to traverse the cssRules array to find the appropriate class (best approach) or hard code the index of the class you want (probably don't do that. It works in the example because there is only one class).
Alternately, I suppose, as a compromise approach you could create a separate 'dynamic styles' stylesheet with only a few rules that might be changed dynamically later on.
Access the document stylesheet and modify the class you want like so:
setTimeout(function(){ // Timeout used only for before/after comparison
var stylesheet = document.styleSheets[0];
stylesheet.cssRules[0].style.width = '50px';
console.log(stylesheet.cssRules[0]);
}, 750);
.item {
width: 100px;
height: 50px;
background-color: #000;
margin: 10px;
display: inline-block;
}
<div class="item">
</div>
<div class="item">
</div>
<div class="item">
</div>

var els = document.querySelectorAll(className);
var index = 0, length = els.length;
for (var i = 0 ; index < length; index++) {
els[index].style.width= "500px";
els[index].style.height= "500px";
}
className just works like normal css selectors, so you can do like "li.Item" for example.
This will affect all the elements with the "Item" class.

Use element.style:
var element = document.getElementsByClassName('Item');
element.style.width = "100px";
just like in this answer
Or you can use jquery:
$(".Item").css("width", "100px");

Your best approach would probably to use the jQuery framework and use its .css() method.
http://api.jquery.com/css/
$('.Item).css('width', '200px')
That should do it.
If you want to do it with vanilla javascript you could try the following:
document.getElementsByClassName("Item").style.width = "300px";

Related

Replace the CSS class in HTML element with its CSS properties in JavaScript

I am trying to get the HTML page's source code using JavaScript (kind of like screenshot). And for styling, I am using external CSS. However, when I get the HTML source code, the styling won't be applied because I won't be able to get the CSS properties for the elements.
So, I am wondering if I can replace the CSS class name with actual CSS properties defined in that class. e.g.
for the HTML element,
<div class="exampleClass"><div>
And CSS,
.exampleClass {
background-color:#FFFFFF;
}
Then the extracted source code using Javascript will be
<div style="background-color:#FFFFFF;"><div>
How can I do this thing in JavaScript?
Thanks
function getCSSPropertiesBySelector(selector) {
return [...document.styleSheets].map(stylesheet => {
var g = [...stylesheet.cssRules].find(rule => rule.selectorText === selector);
if (g) {
return g.style.cssText;
}
}).find(r => r);
}
Mostly based off of https://stackoverflow.com/a/16966533/1799147
getCSSPropertiesBySelector('.logo')
//"display: block; grid-area: I / I / I / I; width: 200px; height: 44px; margin-right: 24px;"
There's probably better ways to do this but it gets the job done. It won't work if there's a duplicate class in this example, you'd probably want it to be changed to append to the properties if you had the same class in another stylesheet
You can assign the desired class to the tag HTML in javascript. For example:
const div = document.createElement('div');
div.className = 'exampleClass';
document.body.appendChild(div);
Or
div.classList.add('exampleClass');

How come changing background color via JavaScript overrides any CSS selectors on my object?

Just a quick question... how is it that if I have the following CSS:
li { background:red; }
li:hover { background:blue; }
With the following JS (or something similar):
document.getElementsByTagName("li")[0].style.backgroundColor="yellow";
My list elements no longer turn blue when I hover over them? I've tested this both on Chrome and FF. And example can be seen here: http://jsfiddle.net/42bQr/. Any ideas?
This is because inline styes are more specific, you can override inline styles with the following:
li:hover { background:blue !important; }
It's because the style is "inline," which takes priority.
Check out this fiddle here to see what's happening: http://jsfiddle.net/9m3qw/
The output of the fiddle is:
<div class="red-bg" style="background-color: yellow;">hello</div>
The reason is because you are setting the style as an inline style which is the most specific. So when you click on a list item, the result is effectively:
<li style="background-color: yellow;">My List Element 1</li>
The following list of selectors is by increasing specificity:
Universal selectors
Type selectors
Class selectors
Attributes selectors
Pseudo-classes
ID selectors
Inline style
To get around this, you could instead assign a class to the list item with:
var listEls = document.getElementsByTagName("li");
for (var i = 0; i <= listEls.length - 1; i++) {
listEls[i].onclick = function () {
this.className = 'yellow'
};
}
where
.yellow {
background:yellow;
}
jsFiddle example
This is happening because you have applied inline style to your selector which has more specifity.
Try this Fiddle
li:hover { background:blue; !important}
If you prefer to use Javascript, then you can use Element ClassList API. But it is only supported in major browsers. Browser Compatibility Matrix. Check out this code
Javascript
var listEls = document.getElementsByTagName("li");
function addYellowClass() {
this.classList.add('bg-yellow');
}
for (var i = 0; i <= listEls.length - 1; i++) {
listEls[i].onclick = addYellowClass;
}
JSBIN Example
As the others have said the inline style takes priority when you click it. You may want to use a hover/mouseover event to add a class ie $(this).addClass('blueBG') with the background of blue that is removed onmouseout if that is the effect you are going for.
"background-color" is more specific than "background" thus it takes priority in your final style. essentially your JavaScript code is overwriting both of CSS properties because it has more weight.
try using background-color as a property in both the CSS and in the JavaScript.

Insert css rule with javascript

I would like to change my div background from time of the day with this code,but doesn't working.I want to add it to my embed css(fourth link). It will add to the remaining rule.
var hur = new Date();
var dyng = hur.getHours()
if(dyng > 6 && dyng < 18){
document.styleSheets[3].cssRules[0].style.background="url('/blog/themes/custom/img/sky.jpg')"
}else{
document.styleSheets[3].cssRules[0].style.background="url('/blog/themes/custom/img/night.jpg')"
}
css
#test {
background-size: cover;
width: 100%;
height: 220px;
}
This typically can be achieved in a simple way by using a pair of jQuery methods:
.addClass()
.removeClass()
In a plain Javascript solution the same can be done with a pair of functions:
element.setAttribute ("class", "CSS class name");
element.removeAttribute ("class", "CSS class name");
Using JavaScript to modify CSS is not a good idea.
It's better to have all your styles defined in CSS and have JavaScript select which of those rules gets applying by adding/removing classes.
You can use the .className property for DOM Elements (but I would recommend using a framework).
You can also use the setAttribute function.
element.setAttribute('class', 'class name');

Update CSS rule property value

I have a html element which is styled (using jquery) with a background image targeted thru its class name.
When I remove the class the background image stays - which is not what I expected or want.
test.html
<div id='log' class='tile'>HELLOWORLD</div>
test.css
.tile{
background: none;
}
test.js
$('.tile').css("background-image", "url(tile.jpg)"); // We see image
$('#log').toggleClass('tile'); // We still see image
After banging my head I think I know whats happening. The css is being applied to the element - NOT to the 'class'.
How can I target a specific css rule so that its key values can be updated?
If that makes sense.
If you wan to change the css rules of the ".tile" class, then you can do it.
There is a post that explains it very well :
function changeBackgroundImage(className, value){
var ss = document.styleSheets;
for (var i=0; i<ss.length; i++) {
var ss = document.styleSheets;
var rules = ss[i].cssRules || ss[i].rules;
for (var j=0; j<rules.length; j++) {
if (rules[j].selectorText === className) {
rules[j].style.backgroundImage = value;
}
}
}
}
You can call it like this :
changeBackgroundImage(".tile","url(tile.jpg)");
The problem is that you´re setting the background-image as an inline stlye that overrides any stylesheet rules. Toggling the class won´t have any affect.
You can either have set the background through a styleheet rule and then add a class that removes it;
#log {
background-image: url(tile.jpg);
}
#log.tile {
background: none;
}
or you could just use !important as;
.tile {
background: none !important;
}
...it might be the other way around but you get the point? :)
try removing class tile and applying new class with bg: none
in effect - when needed apply class with bg, when not needed - without
No need for jQuery in this case. You can use plain old JavaScript. Check out this tutorial:
javascriptkit.com - Changing external style sheets using the DOM
You can't change the class itself without re-writing that declaration in the stylesheet, you ARE working only with the element in the selector.
Try:
$('.tile').css("background-image","none")
$('#log').toggleClass('tile',true);
I would make the background image part of the class as a css style:
.tile {background-image: url('tile.jpg')};
and then remove the class when necessary with jquery
$('#log').removeClass('tile');
you could have two classes in your css...
.tile{
background: none;
}
.tile-w-image
{
background-image: url(tile.jpg);
}
and then with jquery just toggle the classes...
$("#log").toggleClass('tile').toggleClass('tile-w-image');
I'm sure this is just one of many ways of doing this. I hope it helps.
You are very close.
It seems like you are adding inline CSS to your element and then trying to toggle the class. You should keep CSS styling separate in most cases:
HTML:
<div id='log' class='tile'>HELLOWORLD</div>
jQuery (I imagine this should be done on click or another event):
$('#log').toggleClass('tile'); // We still see image
If the "tile" class is already written to the HTML, then toggle-ing it will remove it.
CSS:
.tile{
background-image: url(tile.jpg);
}

Change CSS of class in Javascript?

I've got a class with the display set to none I'd like to in Javascript now set it to inline I'm aware I can do this with an id with getElementById but what's the cleanest way to do it with a class?
You can do that — actually change style rules related to a class — using the styleSheets array (MDN link), but frankly you're probably better off (as changelog said) having a separate style that defines the display: none and then removing that style from elements when you want them no longer hidden.
Do you mean something like this?
var elements = document.getElementsByClassName('hidden-class');
for (var i in elements) {
if (elements.hasOwnProperty(i)) {
elements[i].className = 'show-class';
}
}
Then the CSS
.hidden-class { display: none; }
.show-class { display: inline; }
You can use getElementsByClassName in which you'll get an array of elements. However this is not implemented in older browsers. In those cases getElementsByClassName is undefined so the code has to iterate through elements and check which ones have the desired class name.
For this you should use a javascript framework such as jQuery, mootools, prototype, etc.
In jQuery it could be done with a one-liner as this:
$('.theClassName').css('display', 'inline')
you can create new style rule instead.
var cssStyle = document.createElement('style');
cssStyle.type = 'text/css';
var rules = document.createTextNode(".YOU_CLASS_NAME{display:hidden}");
cssStyle.appendChild(rules);
document.getElementsByTagName("head")[0].appendChild(cssStyle);
$("#YOUR_DOM_ID").addClass("YOUR_CLASS_NAME");
You may like to exploit/rewrite this function:
function getStyleRule(ruleClass, property, cssFile) {
for (var s = 0; s < document.styleSheets.length; s++) {
var sheet = document.styleSheets[s];
if (sheet.href.endsWith(cssFile)) {
var rules = sheet.cssRules ? sheet.cssRules : sheet.rules;
if (rules == null) return null;
for (var i = 0; i < rules.length; i++) {
if (rules[i].selectorText == ruleClass) {
return rules[i].style[property];
//or rules[i].style["border"]="2px solid red";
//or rules[i].style["boxShadow"]="4px 4px 4px -2px rgba(0,0,0,0.5)";
}
}
}
}
return null;
}
to scan all style sheets attached pass "" as third argument, otherwise something like "index.css"
ruleClass contains starting '.'
if (rules[i].selectorText && rules[i].selectorText.split(',').indexOf(property) !== -1) condition improvement found here https://stackoverflow.com/a/16966533/881375
don't forget to use javascript syntax over css properties, e.g. box-shadow vs. boxShadow
Although this is long gone, here a few remarks:
Using display: inline to make things visible again may spoil the
page flow. Some elements are displayed inline, others block etc. This
should be preserved. Hence, only define a .hidden style and remove it
to make things visible again.
How to hide: There are (at least) two ways to hide elements, one is
the above mentioned display: none which basically makes the element
behave as if it was not there, and the visibility: hidden which
renders the element invisible but keeps the space it occupies.
Depending on what you want to hide, the visibility may be a better
choice, as other elements will not move when showing/hiding an
element.
Adding/removing classes vs. manipulating CSS rules: The result is
quite different. If you manipulate the CSS rules, all elements having
a certain CSS class are affected - now and in the future, i.e. new
elements dynamically added to the DOM are also hidden, whereas when
you add/remove a class, you must make sure that newly added elements
also have the class added/removed. So, I'd say adding/removing
classes works well for static HTML, whereas manipulating CSS rules
might be a better choice for dynamically created DOM elements.
To change CLASS you need to edit document stylesheets
[...document.styleSheets[0].cssRules].find(x=> x.selectorText=='.box')
.style.display='inline';
[...document.styleSheets[0].cssRules].find(x=> x.selectorText=='.box')
.style.display='inline';
.box {
margin: 10px;
padding: 10px;
background: yellow;
display: none
}
<div class="box" >My box 1</div>
<div class="box" >My box 2</div>
<div class="box" >My box 3</div>
Best way to do it is to have a hidden class, like so:
.hidden { display: none; }
After that, there is a className attribute to every element in JavaScript. You can just manipulate that string to remove occurrences of the hidden class and add another one.
One piece of advice: Use jQuery. Makes it easier to deal with that kind of stuff, you can do it like:
$('#element_id').removeClass('hidden').addClass('something');

Categories