Get a css parameter without creating an element [duplicate] - javascript

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

Related

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.

CSS selector for all elements starting with a prefix

I have several polymer elements.
<ps-el-one/>
<ps-el-two/>
<ps-el-three/>
<ps-el-four/>
I want to be able to query all of the elements which begin with "ps-" with either a CSS selector or javaScript.
I whipped up the following solution, but I am wondering if there is anything more efficient?
var allElementsOnPage = document.querySelectorAll('*');
var res = [];
for (var index in allElementsOnPage) {
var el = allElementsOnPage[index];
if (el && el.tagName && el.tagName.substr(0, 3) == 'PS-') {
res.push(el);
}
}
This solution seems very inefficient.
I'm not aware of any element selector, but it is possible with CSS3 attribute and class substring-matching selectors (which are supported in IE7+):
[class^="tocolor-"], [attr*=" tocolor-"] {
color:red
}
Not sure if this is what you want, but probably gives you another way of achieving the same.
Check this here
<input name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">
<script>
$( "input[name*='man']" ).val( "has man in it!" );
</script>
You can use something like this instead of querySelectorAll
function myFunction() {
var x = document.getElementsByTagName("*");
var res = [];
for(var i = 0; i < x.length; i++) {
if(x[i].tagName.indexOf('PS-') == 0) {
res.push(x[i]);
}
}
}
Just give a class to all the elements common in nature. and do:
HTML
<ps-el-one class="ps"/>
<ps-el-two class="ps"/>
<ps-el-three class="ps"/>
<ps-el-four class="ps"/>
CSS
// for all elements together
.ps { /* css for all elements together */ }
// for individual elements
.ps:nth-of-type(1) { /* css for 1st ele */ }
.ps:nth-of-type(2) { /* css for 2nd ele */ }
.ps:nth-of-type(3) { /* css for 3rd ele */ }
.ps:nth-of-type(4) { /* css for 4th ele */ }
JS
// for all elements together
var ps = document.querySelectorAll('.ps');
// for individual elements
var ps1 = document.querySelectorAll('.ps')[0];
var ps2 = document.querySelectorAll('.ps')[1];
var ps3 = document.querySelectorAll('.ps')[2];
var ps4 = document.querySelectorAll('.ps')[3];

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.

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

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

JavaScript get Styles

Is it possible to get ALL of the styles for an object using JavaScript? Something like:
main.css
-------
#myLayer {
position: absolute;
width: 200px;
height: 100px;
color: #0000ff;
}
main.js
-------
var ob = document.getElementById("myLayer");
var pos = ob.(getPosition);
// Pos should equal "absolute" but
// ob.style.position would equal null
// any way to get absolute?
You are talking about what is known as Computed Style, check out these article on how to get it:
Get Styles on QuirksMode
Get Computed Style
Get the rendered style of an element
From the last article, here is a function:
function getStyle(oElm, strCssRule){
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle){
strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
}
else if(oElm.currentStyle){
strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
return p1.toUpperCase();
});
strValue = oElm.currentStyle[strCssRule];
}
return strValue;
}
How to use it:
CSS:
/* Element CSS*/
div#container{
font: 2em/2.25em Verdana, Geneva, Arial, Helvetica, sans-serif;
}
JS:
var elementFontSize = getStyle(document.getElementById("container"), "font-size");
You might use:
var ob = document.getElementById("myLayer");
var pos = ob.style.position;
Every CSS property has it's own object model. Usually those css properties that contain '-' are written using java model.
For example:
//getting background-color property
var ob = document.getElementById("myLayer");
var color = ob.style.backgroundColor;
If you want to get all the css properties that are defined for an object, you will have to list them one by one, because even if you did not set the property in your style sheet, an object will have it with the default value.
Polyfill to get the current CSS style of element using javascript ... Visit the link for more info
/**
* #desc : polyfill for getting the current CSS style of the element
* #param : elem - The Element for which to get the computed style.
* #param : prop - The Property for which to get the value
* #returns : The returned style value of the element
**/
var getCurrentStyle = function (ele, prop) {
var currStyle;
if (!window.getComputedStyle) {
currStyle = ele.currentStyle[prop];
} else {
currStyle = window.getComputedStyle(ele).getPropertyValue(prop);
}
return currStyle;
}
/** How to use **/
var element = document.getElementById("myElement");
getCurrentStyle(element, "width"); // returns the width value

Categories