JavaScript Element Style

get HTML element style with Javascript

use window.getComputedStyle

read more https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

basically style property only read the inline style on the element

How to get an HTML element's style values in JavaScript?

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 CCS 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).

Also, the IE element.currentStyle will return all the sizes in the unit that they were specified, (e.g. 12pt, 50%, 5em), the standard way will compute the actual size in pixels always.

I made some time ago a cross-browser function that allows you to get the computed styles in a cross-browser way:

function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hypen 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;
}
}

The above function is not perfect for some cases, for example for colors, the standard method will return colors in the rgb(...) notation, on IE they will return them as they were defined.

I'm currently working on an article in the subject, you can follow the changes I make to this function here.

Why element.style always return empty in JS?

element.style returns the inline style used in html document and since the style is not set directly in html you will get and empty value

What you are looking for is the computedStyle which will returns the style that is applied to the element

console.log(window.getComputedStyle(document.getElementById('test')).display)
#map {      display: block;      align-content:center;    }
<div id="test">test</div>

Set HTML element's style property in javascript

You can try grabbing the cssText and className.

var css1 = table.rows[1].style.cssText;
var css2 = table.rows[2].style.cssText;
var class1 = table.rows[1].className;
var class2 = table.rows[2].className;

// sort

// loop
if (i%2==0) {
table.rows[i].style.cssText = css1;
table.rows[i].className = class1;
} else {
table.rows[i].style.cssText = css2;
table.rows[i].className = class2;
}

Not entirely sure about browser compatibility with cssText, though.

why are initial CSS styles not visible on DOM element.style field?

The HTMLElement.style property is not useful for completely
learning about the styles applied on the element, since it represents
only the CSS declarations set in the element's inline style
attribute
, not those that come from style rules elsewhere, such as
style rules in the section, or external style sheets. To get
the values of all CSS properties for an element you should use
Window.getComputedStyle() instead.

Via- MDN Web Docs | Getting Style
Information


HTMLElement.style:

The HTMLElement.style property is used to get as well as set the inline style of an element.

console.log(document.getElementById("para").style.fontSize); // will work since the "font-size" property is set inlineconsole.log(document.getElementById("para").style.color); // will not work since the "color" property is not set inline
#para {color: rgb(34, 34, 34);}
<p id="para" style="font-size: 20px;">Hello</p>

Set style using pure JavaScript

document.getElementsByTagName('div')[0].style.backgroundColor = 'RED';
<div>sample</div>

How to change style properties of an element in JavaScript?

The problem is that the script runs before the DOM is fully constructed and the element that you want to style actually exists.

You need to move your <script> tag to the end of the <body> element:

 <body>
<div id="background" class="content">
<!-- <img src="Temp1.jpg" alt="Greeting card image"> -->
<h1 id="Title" class="text">Sample title text</h1>
<h2 id="Name" class="text">Sample name text</h2>
<h3 id="Message" class="text">Sample message text</h3>
</div>
<script src="script.js"></script>
</body>

Javascript Element.style CSSStyleDeclaration object's properties look wierd?

The CSSStyleDeclaration object is a bit exotic. If you look at btn.style["background-color"] or btn.style.backgroundColor directly, you'll see red (or some representation of red, it varies by browser).

const btn = document.querySelector('#btn');
btn.style['background-color'] = 'red';

btn.addEventListener('click', () => {
console.log(btn.style["background-color"]);
console.log(btn.style.backgroundColor);
});
<button id="btn">Click Me</button>


Related Topics



Leave a reply



Submit