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');
Related
Im implementing multiple rangesliders into my site and because this is code generated in real time I need to select some elements by their parents parent class.
this is the code the timeline class is the last one i can set myself and i need to be able to edit the .irs-line-right without changing my other sliders
In your question you stated that you want to access an element through a parent element. I don't see why this is necessary, but it's surely possible. You can change the element style, attribute, etc. through js. However, it's best to simply use css if you only need to change the style of the span with the class 'irs-line-right'. I'll show how to do this in both css and javascript.
CSS Example
In css you can change the style of the 'irs-line-right'
by referencing the 'timeline' div (and no other ids or classes) as follows:
https://jsfiddle.net/2t3w0826/
.timeline > div:nth-of-type(2) > span > span > span > span:nth-of-type(3)
{
background-color: red;
}
Javascript Example
https://jsfiddle.net/8qceLgw8/
var array_of_all_timelines = document.getElementsByClassName("timeline");
for(var loop=0; loop < array_of_all_timelines.length; loop++)
{
var element_irs_line_right = array_of_all_timelines[loop].children[1].children[0].children[0].children[0].children[2];
element_irs_line_right.style.backgroundColor = "red";
};
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";
Say I have a table whose rows can be dynamically assigned .hidden classes. Rows with that class are hidden via CSS. The rows are also styled with alternating colours, like so:
tr:nth-child(even) {
background-color: $light-grey;
}
However, I want every even, unhidden row to be shaded. So hidden rows are not counted when :nth-child(even) is applied, and the pattern appears consistent. The following is my immediate attempt, but it doesn't do what I'm hoping for.
tr:not(.hidden):nth-child(even) {
background-color: $light-grey;
}
:nth-child() is simply referring to the rows' original indices, not the current selection scope from tr:not(.hidden). The two are simply 'filtered through' on top of one another.
Is there a :nth-of-scope/selection() (or simply :nth()) meta class in CSS? Are there any equivalents or alternate methods?
Or must I resort to Javascript?
(I should say that I can also use jQuery)
There is no way to do this in pure CSS as adding display:none or visibility:none doesn't remove the elements from the DOM, which is what CSS uses.
As a result, you will need to add a little JavaScript (which runs once the page has loaded) to do this, like so
var trs = document.getElementsByTagName("tr"), // Select whichever ones you need
count = 0; // Counter for the non-hidden ones
for(var i = 0; i < trs.length; i++) {
if(!trs[i].classList.contains("hidden") && (count++)%2 == 0) { // Odd ones
trs[i].style.background = "black";
} else if(!trs[i].classList.contains("hidden")) { // Even ones
trs[i].style.background = "lightgrey";
}
}
Turns out using jQuery is much simpler than any sort of CSS hack:
rows = $('table tbody tr');
rows.find('tr:visible:odd').css('background-color', '#f7f7f7');
And to specify styles for both even and odd:
rows.find('tr:visible').each(function(i) {
if (i%2) {
$(this).css('background', '#f7f7f7');
} else {
$(this).css('background', 'none');
};
});
I know, I've answered by own question—I should have made it clear that I can use jQuery!
I just wish :visible and :even would hurry up and make it into the CSS standard.
I've just managed to solve this by just adding an extra <tr> element with display: none; set (via CSS in my case but could use a style attribute) when a block of hidden rows has an odd number of elements. This won't meet every use case, but for cases where you're using multiple rows to create expanding tables it works quite well.
Not sure this is possible with pure CSS. Using display:none; and visibility:hidden; the items still exist in the DOM and so the table background color is displayed incorrectly. You can get this to work using JQuery remove() You can see my simple example on js.fiddle here
Pure CSS (no JS) solution:
The trick is to hide a row with different tag, not class. "ul/li" tags must go. In my example I use "del" tag to hide.
.list div:nth-of-type(odd) { background: ghostwhite; }
.list del { display: none; }
<div class="list">
<div>1</div>
<div>2</div>
<div>3</div>
<del>4</del>
<div>5</div>
<del>6</del>
<div>7</div>
</div>
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.
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);
}