I have below CSS and and has one JavaScript file where I am getting Width property value say 50px.
I want to put that JavaScript Width property Value to below CSS
.carpe_slider_slitss {
BORDER-LEFT: #5256BB 1px solid; WIDTH: 100px; COLOR: #5256BB;
}
so the above CSS should look likes
.carpe_slider_slitss {
BORDER-LEFT: #5256BB 1px solid; WIDTH: 50px; COLOR: #5256BB;
}
So, how can I pass that JavaScript value to Width property value of CSS.
Please help.
element.style.width = '50px';
Where element is a reference to the element.
You can not manipulate external file via javascript. If your class is located in an external css file then you can not change that.
What all developers do is changing classes that located in current html file or changing style attribute
if you want to change the css styleSheet rules for all elements, you can do that with simple javascript:
function findCssRule(cssSelectorName)
{
var stylesheets = document.styleSheets;
for(var i = 0, ii = stylesheets.length;i<ii;i++)
{
for(var j = 0, jj = stylesheets[i].rules.length;j<jj;j++)
{
if(stylesheets[i].rules[j].selectorText == cssSelectorName)
{
return stylesheets[i].rules[j];
}
}
}
return null;
}
//set the width to 80px for '.carpe_slider_slitss' css rule
var cssRule = findCssRule('.carpe_slider_slitss');
if(cssRule!=null)
cssRule.style.width = '80px';
this is a way to do it
//ether create a new style sheet
var style = document.createElement ("style");
document.getElementByTagName('head')[0].appendChild(style);
//or find a document you want to edit
//ether local
var style = document.getElementByTagName('style')[0];
//or imported
var style = document.getElementByTagName('style')[0];
style = style.sheet ? style.sheet : style.styleSheet;
if(style.insertRule){
//insertRule('your css code',new rule index);
style.insertRule('carpe_slider_slitss{ width: 50px; }', style.cssRules.length); //You can use 0 to insert your rule at the start of the style
}else{ //this is the ie < 9 way
style.addRule('carpe_slider_slitss', 'width: 50px', style.cssRules.length);
}
Related
I created 3 radio buttons and a label for each of them using JavaScript. When I try adding for in the label using htmlFor, it doesn't apply it to the actual DOM Element. Meaning, when I try using the label on the webpage, it doesn't select the radio button.
I checked in the developer tools, and saw that the labels did not have for applied to them.
What am I doing wrong, and how can I fix it?
JSFiddle
var _doc = document,
sliderWrapper = _doc.getElementById('sliderWrapper'),
radioWrapper = _doc.createElement('div');
for (var i = 0; i < 3; i++) {
var radio = _doc.createElement('input');
var niceRadio = _doc.createElement('lable');
var index = radioWrapper.children.length / 2;
niceRadio.className = 'niceRadio';
niceRadio.htmlFor = radio.id = 'sliderRadio' + index;
radio.type = 'radio';
radio.name = 'myName';
radioWrapper.appendChild(radio);
radioWrapper.appendChild(niceRadio);
console.log(niceRadio.htmlFor);
}
sliderWrapper.appendChild(radioWrapper);
.niceRadio {
position: relative;
width: 20px;
height: 20px;
cursor: pointer;
border-radius: 50%;
border: 5px solid orange;
}
.niceRadio:hover {
border-color: lightblue;
}
<div id="sliderWrapper">
</div>
The htmlFor is used to bind a label to a specific form element. However, it uses the id of that form element (not the name).
Source MDN:
The HTMLLabelElement.htmlFor property reflects the value of the for
content property. That means that this script-accessible property is
used to set and read the value of the content property for, which is
the ID of the label's associated control element.
Also, in your fiddle, you misspelled label.
Updated fiddle: https://jsfiddle.net/h09mm827/2/
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.
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
How to write css code in javascript? (Uncaught TypeError: Cannot set property "height" of undefined)
javascript
document.getElementById("slideshow").getElementsByClassName("arrow").style.height = "86px";
css
#slideshow .arrow{
height:86px;
width:60px;
position:absolute;
background:url('arrows.png') no-repeat;
top:50%;
margin-top: -43px;
cursor: pointer;
z-index: 5000;
}
The key here is the pluralisation of getElementsByClassName - elements. This method returns an array-like object of elements, not just one element.
To apply the style to each, you need to loop through this array-like object and add the styles to each individual element returned:
var elems = document.getElementById("slideshow").getElementsByClassName("arrow");
for (var i = 0; i < elems.length; i++)
elems[i].style.height = "86px";
document.getElementsByClassName returns an array.
You have to loop through it, or if you know the index, do this:
document.getElementById("slideshow").getElementsByClassName("arrow")[0].style.height = "86px";
or
document.getElementById("slideshow").getElementsByClassName("arrow")[i].style.height = "86px";
i being your loop variable.
A bit of theory:
Changing HTML Style
To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=new style
Here is the example:
// JavaScript demonstration
var changeBg = function (event) {
console.log("method called");
var me = event.target
, square = document.getElementById("square");
square.style.backgroundColor = "#ffaa44";
me.setAttribute("disabled", "disabled");
setTimeout(clearDemo, 2000);
}
function clearDemo(button) {
var square = document.getElementById("square");
square.style.backgroundColor = "transparent";
button.removeAttribute("disabled");
}
var button = document.querySelector("button");
button.addEventListener("click", changeBg);
console.log(button);
#square {
width: 20em;
height: 20em;
border: 2px inset gray;
margin-bottom: 1em;
}
button {
padding: .5em 2em;
}
<h1>JavaScript sample</h1>
<div id="square"></div>
<button>Click Me</button>
JavaScript-Based Style Sheets - http://www.w3.org/Submission/1996/1/WD-jsss-960822
Mozzila's Web Developer guide - https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/JavaScript
While I've started with explanation and theory #James Donnelly already provided my answer, which I've wanted to use:
var elements = document.getElementById("slideshow").getElementsByClassName("arrow");
for (var i = 0; i < elems.length; i++) {
elems[i].style.height = "86px";
.
As someone already pointed out,
document.getElementsByClassName returns an array (N Objects)
while
document.getElementById returns an element (ONE object)
This is because N elements can have the same class but only ONE item can have a particular ID.
Since you can't edit more items' attribute at once, you must cycle them and edit the attribute of each one by one
document.getElementById("slideshow").getElementsByClassName("arrow")[0].style.height = "86px";
document.getElementById("slideshow").getElementsByClassName("arrow")[1].style.height = "86px";
document.getElementById("slideshow").getElementsByClassName("arrow")[2].style.height = "86px";
.....
document.getElementById("slideshow").getElementsByClassName("arrow")[N].style.height = "86px";
This can be achieved by using a for cycle or a each one.
This question already has answers here:
Can jQuery get all CSS styles associated with an element?
(5 answers)
Closed 8 years ago.
Suppose in my style sheet:
.test{width: 20px; height: 50px; color: blue;}
.some-test{padding: 20px; margin: 10px;}
.even-test{font-size: 20px; color: red;}
Is it possible to detect the 20px value of each css properties so that I could replace it?
I'm supposing to detect something like this:
$('.selector').filter(function() {
return $(this).css(property) === '20px';
}).css(property, value);
Isn't there anything something like: style.arguments[] ?
You can use the filter function in jQuery to find all elements that have that width.
$('.allYourSelectors').filter(function() {
return $(this).css('width') === '20px';
}).css("width", newWidth);
However, it would be much better to just give them all the same class that you can modify.
To search through CSS styles (not sure if this gets style="..." styles):
var parseStyle = function(rules) {
for (var i = 0; i < rules.length; ++i)
{
console.log(rules[i].style.width);
}
};
//care needs to be taken as to when this executes - styles may not have been loaded yet
for (var i = 0; i < document.styleSheets.length; ++i)
if (document.styleSheets[i].rules && document.styleSheets[i].rules.length > 0)
parseStyle(document.styleSheets[i].rules);
If it's not the CSS properties you want but the result of the style on an element, this might be more what you're after...
var element = ... jquery or whatever
var elementStyle = element.currentStyle || getComputedStyle(element);
console.log(elementStyle.width);