how can I detect the css value with jquery? [duplicate] - javascript

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);

Related

Get a css parameter without creating an element [duplicate]

This question already has an answer here:
Query property value of a css class even if not in use
(1 answer)
Closed 7 years ago.
I dispose of the following class :
.specialCell {
padding-left: 10px;
}
I would like to use this value as a property in JS, eg
var specialCellLeftPadding = getCssValue('.specialCell', 'padding-left');
The only way I can think of would be to create an element with the wanted class and get the seeked attribute value :
var tmpElt = document.createElement('div');
tmpElt.className = 'specialCell';
document.body.appendChild(tmpElt);
var specialCellLeftPadding = getComputedProperties(tmpElt).getPropertyValue('padding-left');
document.body.removeChild(tmpElt);
Is it possible to achieve the same purpose without creating and adding an new element to the dom ? (assuming no element with this class exists).
You can query CSS information directly from stylesheets using the CSSOM. E.g.,
var stylesheet = document.styleSheets[0];
document.getElementById('output').innerHTML = stylesheet.cssRules[0].style.paddingLeft;
.test { padding-left: 12px; }
Padding left: <span id="output"></span>
Borrowing from the example of dystroy's answer, you can get a css value using the document.styleSheets property
Using the css
.specialCell {
padding-left: 10px;
}
and
function getCssProperty(cssclass, property) {
for (var i = 0; i < document.styleSheets.length; i++) {
var styleSheet = document.styleSheets[i];
var cssRules = styleSheet.rules || // chrome, IE
styleSheet.cssRules; // firefox
for (var ir = cssRules.length; ir-- > 0;) {
var rule = cssRules[ir];
if (rule.selectorText == "." + cssclass) {
return rule.style.getPropertyValue(property);
}
}
}
}
var prop = getCssProperty('specialCell', 'padding-left');
console.info(prop);
this example will print 10px in the console

How to write css code in javascript? (Uncaught TypeError: Cannot set property "height" of undefined)

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.

Add CSS Class Property through Javascript

I have an HTML page having css class for a control with following definition:
.ms-crm-Inline-Edit select.ms-crm-SelectBox {
border: 1px solid #CCCCCC;
font-size: 12px;
margin: 1px 0 0 1px;
width: 100%;
}
I need to add a new attribute to this class as follows:
height: "120px !important";
This has to be done through Javascript. I can't modify origional class definition that's why I have to add Javascript function which does this job. For that purpose I have written Jscript method but its not working.
function CustomizePicklistHeight ()
{
document.getElementsByClassName('ms-crm-Inline-Edit select.ms-crm-SelectBox').style.height = '120px !important';
}
I guess, first we have to add height attribute to this class but I dont know how to do that in JScript. Please suggest.
document.getElementsByClassName returns an array of all items with that class.
Try this:
function CustomizePicklistHeight()
{
// Store elements for each class differently. Just in case :)
var elements1 = document.getElementsByClassName('ms-crm-Inline-Edit');
var elements2 = document.getElementsByClassName('ms-crm-SelectBox');
// Since you cant affect the array directly, you use a loop to do the operation on each individual element
for (var i = 0; i < elements1.length; i++)
{
element1[i].style.height = '120px !important';
};
for (var j = 0; j < elements2.length; j++)
{
element1[j].style.height = '120px !important';
};
}​
Hope this helps.. :)
var matches = document.querySelectorAll(".ms-crm-Inline-Edit, select.ms-crm-SelectBox");
for(i=0; i<matches.length; i++)
{
matches[i].style.height = '120px !important';
}
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll
ClassName means "class name" (ms-crm-SelectBox) not "Entire selector". (querySelector and querySelectorAll let you use complete selectors though.
Elements means "elements" (plural) not "Element". It returns a NodeList, which you can loop over like an array.
If, on the other hand, you want to the modify the CSS rule-set instead of the styles applied directly to the HTML elements, then you need to look at document.styleSheets instead.
you will have to make a loop by setting each item, and if you have not "! important" earlier you do not need it.

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;');

javascript value to css

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);
}

Categories