Use css property in javascript

Get/Set CSS property values via Javascript: questions

1) Isn’t it possible to directly get global border color of a div if there is only one color, the same for each side:

computedStyle.getPropertyValue("border-color"); 
computedStyle.getPropertyValue("border-left-color"); 
computedStyle.getPropertyValue("border-right-color"); 
computedStyle.getPropertyValue("border-top-color"); 

. 2) When having style properties in a CSS file, they are only accessible through the getComputedStyle method and not via the style property like style properties defined inline, via a style attribute in the div, I’m right?

myDiv.style.getPropertyValue("border-left-color"); 

This will not work. 3) If we want to set a style property, we have to use the style attribute of the element, is it not possible using the computed style object?

computedStyle.setProperty("border-color", "yellowgreen", null); 

I thought using the style attribute was the «old way to do», like using the inline style attribute or using object.style.property = «value» to set a style property in Javascript. Thanks. jsFiddle: http://jsfiddle.net/pgtFR/12/

I dunno, it depends on your definition of «magic»; personally I think jQuery is pretty damn magical 🙂 But yeah I’m not aware of anything jQuery does that would specifically solve this post.

3 Answers 3

1) Isn’t it possible to directly get global border color of a div if there is only one color, the same for each side:

Yes, its possible to get the computed style by just using the shorthand property name. I tried the example you have shared on jsfiddle and computedStyle.getPropertyValue(«border-color») does return (265,65,0) which is the rgb code for orange as expected.

2) When having style properties in a CSS file, they are only accessible through the getComputedStyle method and not via the style property like style properties defined inline, via a style attribute in the div, I’m right?

Yes. getComputedStyle returns the final computed style value by the browser after applying external, internal and inline style rules. .style attribute only refers to the inline style for the element.

3) If we want to set a style property, we have to use the style attribute of the element, is it not possible using the computed style object?

No. According to this document, getComputedStyle returns a CSSStyleDeclaration object which is read-only.

Thanks, very useful answer! You’re right, computedStyle.getPropertyValue(«border-color») works but not in Firefox and it returns rgb(255, 165, 0) not (265,65,0). I’ve noticed that in Chrome, myDiv.style.setProperty(«border-color», «yellowgreen», null); with alert(myDiv.style.getPropertyValue(«border-left-color»)); returns «rgb(154, 205, 50)» and not «yellowgreen» wich is I think the correct/standard way it should be displayed. I’ve seen many times that Chrome doesn’t respect standards as it should be, so maybe Firefox is right.

For information, it is possible to access some CSS properties like width and height via element.style even if they were defined in a stylesheet instead of inline: stackoverflow.com/questions/34378543/…

Isn’t it possible to directly get global border color of a div if there is only one color, the same for each side

Yes and No. The spec describes two methods:

  • getPropertyCSSValue() returns a CSSValue of a single CSS Property. It does not work with shorthand properties.
  • getPropertyValue() returns a DOMString , and works also for shorthand properties. But you need to be careful when there are different borders, the string will represent all of them.

When having style properties in a CSS file, they are only accessible through the getComputedStyle method

No. They are also accessible through document.styleSheets (spec), and can be changed with the StyleSheet interface.

. and not via the style property like style properties defined inline, via a style attribute in the div, I’m right?

Yes. The .style property represents only the style declaration in the style attribute (inline styles).

If we want to set a style property, we have to use the style attribute of the element

I guess you mean a CSS property. You can also influence the computed style by setting classes on your element (or anything else that applies other styles through a stylesheet). Or you can create stylesheets dynamically, and they will be applied on the document. You can also set the style attribute of an element, but usually you will use the CSSStyleDeclaration interface exposed by the .style property.

is it not possible using the computed style object?

Yes. The spec says that the returned » CSSStyleDeclaration is read-only and contains only absolute values«.

Читайте также:  Write file php utf8

Thanks for those great answers. Yes I meant a CSS property, we always have to use .style attribute to set a property value?

Are you sure that getPropertyValue() works for shorthand properties? See this question stackoverflow.com/q/40830568/1325646

@pomber Yes, but a CSSStyleDeclaration doesn’t necessarily contain shorthand properties. It seems getComputedStyle doesn’t compute shorthands, for example, but if you retrieve a .style or something you should be able to access them.

Ok, first off let’s address this:

I thought using the style attribute was the «old way to do», like using the inline style attribute or using object.style.property = «value» to set a style property in Javascript.

The style property in JS is very different from inline styles in HTML. Inline styles in HTML are bad (IMHO) because:

  1. They are rough on your designer; if you change blue to lightBlue, and you had a class «blue», you have one place to change (your stylesheet). If instead you had a document full of style=’color:blue’ . well now you get to have some fun with using the Linux sed command to do a massive find/replace 😉
  2. Classes work better performance-wise. For one thing, page load-wise, style=’color:blue’ is six more characters than class=’blue’ . When you start having multiple classes/styles, and lots of elements with all those, it (kind of) adds up. Similarly, once you enter JS land, changing classes on things is slightly faster than changing styles directly. PPK did a study on this awhile back on his quirksmode.org blog.

But the thing is, browsers have changed a lot since PPK did that study, and changing classes at best saves a few ms vs. changing styles. Similarly, the page size will change with classes vs. styles, but with today’s bandwidth the change won’t be significant unless you have some truly horrible markup.

Читайте также:  Индекс наименьшего элемента массива python

So, at the end of the day, classes and stylesheets are preferred primarily for reason #1; trying to maintain a consistent look, or even a not-fugly-but-inconsistent look, is basically almost impossible with inline styles. Maybe if you do a huge amount of server-side processing to generate those inline styles . but I wouldn’t recommend it.

However, none of that precludes using the JS property «style» though. In fact, if you look at the source for jQuery, you’ll see that it’s filled with uses of .style . And jQuery isn’t just the most popular library on the web; it’s all (originally) John Resig code, which means it’s as good, quality-wise, as JS code gets.

So yeah, use style. Don’t feel guilty about it 🙂

Now, as for the rest of your questions, the short answer is that getComputedStyle is essentially the JS reference to the stylesheets, and as such you can’t alter them (no to 3), they don’t have inline styles (yes to 2) and I’m honestly not sure what the different browsers do in the 1) case; I wouldn’t expect anything consistent, but you might get lucky.

Источник

Get a CSS value with JavaScript

But, can I get a current specific style value? I’ve read where I can get the entire style for the element, but I don’t want to have to parse the whole string if I don’t have to.

Your question lends to believe you want something like var top = document.getElementById(‘image_1’).style.top; May want to rephrase it if that’s not what you want

Thx All, both methods work perfectly, just what I needed. The Jquery method is a bit more compact, so I’ll probably use that.

8 Answers 8

var element = document.getElementById('image_1'), style = window.getComputedStyle(element), top = style.getPropertyValue('top'); console.log(top);

If you want to change background color of a div for example, be careful to NOT USE «backgroundColor» instead of «backgroung-color» 😉

Somewhat off topic: some (all?) shorthand css properties are not accessible in JavaScript. E.g. you can get padding-left but not padding. JSFiddle

@DavidWiniecki i dont really believe webdevs should still consider IE8 a mainstream browser. considering it is no longer supported by microsoft

Читайте также:  Get size of php array

The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.

Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle method.

The two ways have differences, for example, the IE element.currentStyle property expect that you access the CSS property names composed of two or more words in camelCase (e.g. maxHeight, fontSize, backgroundColor, etc), the standard way expects the properties with the words separated with dashes (e.g. max-height, font-size, background-color, etc). .

function getStyle(el, styleProp) < var value, defaultView = (el.ownerDocument || document).defaultView; // W3C standard way: if (defaultView && defaultView.getComputedStyle) < // sanitize property name to css notation // (hyphen separated words eg. font-Size) styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase(); return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp); >else if (el.currentStyle) < // IE // sanitize property name to camelCase styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) < return letter.toUpperCase(); >); value = el.currentStyle[styleProp]; // convert other units to pixels on IE if (/^\d+(em|pt|%|ex)?$/i.test(value)) < return (function(value) < var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left; el.runtimeStyle.left = el.currentStyle.left; el.style.left = value || 0; value = el.style.pixelLeft + "px"; el.style.left = oldLeft; el.runtimeStyle.left = oldRsLeft; return value; >)(value); > return value; > > 

Источник

Getting or changing CSS class property with Javascript using DOM style

My objective is to change the background color of a columns in a table without addressing each data entry individually by Id or Name. I know there are several ways to do this, and I’ve tried 3 to be exact, and I’m having problems with each. For the sake of simplicity and clarity, In this question, I’m asking how to successfully do it using the element.style.backgroundColor object in the DOM. Here’s my HTML:

         
Column 1 Header Column 2 Header
R1 C1 R1 C2
R2 C1 R2 C2

I have a feeling it has something to do with the data type returned by the document.getElementsByClassName DOM object. The referenced website says it returns an HTMLcollection. Other places I’ve found says it returns a «list» of elements. I tried making an array and assigning the result to the array and accessing each element in the array with a loop, but got the same error at the same place. It might be that I just don’t know how to handle a, «collection.» At any rate, I was expecting, «lime» or the hex or rgb equivalent because that’s what I defined in the CSS file. I want to be able to change it with Javascript. Any help would be much appreciated. Thanks! EDIT: Added arguments to Shylo Hana’s Answer to make it more modular

function testerFunction() < changeColumnColor('col1','blue'); >function changeColumnColor(column,color) < var cols = document.getElementsByClassName(column); for(i=0; i> 

Источник

Оцените статью