Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get css property value in pure javascript

I want to get the width of an element in percentage. I am using the following function to get the style but it gives the value in pixels. Here the variable style can be any css property like width, height etc.

this.getStyle = function(style) {
    var elementStyle = window.getComputedStyle(that.element);
    var value = elementName.getPropertyValue(style);
    return value;
}
like image 409
Romit Amgai Avatar asked Dec 20 '15 06:12

Romit Amgai


People also ask

How do I retrieve the properties of a CSS element?

You can get the computed value of an element's CSS property by simply passing the property name as a parameter to the css() method. Here's the basic syntax: $(selector). css("propertyName");

Can we change CSS property value using JavaScript?

CSS variables have access to the DOM, which means that you can change them with JavaScript.

What is the property value of CSS?

The used value of a CSS property is its value after all calculations have been performed on the computed value. After the user agent has finished its calculations, every CSS property has a used value. The used values of dimensions (e.g., width , line-height ) are in pixels.

Can you put CSS in JavaScript?

The CSS file is used to describe how HTML elements will be displayed. There are various ways to add CSS file in the HTML document. JavaScript can also be used to load a CSS file in the HTML document.


2 Answers

I think you get always pixels, rather than % width. The reason is while object render it always set physical width based on% we given, this you can verify via dom. Javascript use DOM(Document Object Model), while jQuery you can use Dom as well as before load property via document.getready().

So as above you can get the property, but in pixels.

document.getElementById('yourdivname').element.style.width

or

div2 = document.getElementById('div2');
alert("Width of div2 with style = " + div2.style.width);

Getting the width of an html element in percent % with jQuery

This is interesting :

  1. Is it possible to use jQuery to get the width of an element in percent or pixels, based on what the developer specified with CSS?

  2. http://www.lucemorker.com/blog/javascript-vs-jquery-quick-overview-and-comparison

$(document).ready is a jQuery event to be triggered after the HTML document has been loaded vs onload is a built-in DOM event to be triggered after all content has been loaded. So the ready event would normally fire earlier than the onload event, allowing code execution as early as possible without having to wait for all assets to be fully loaded

For more details :- click this link.

like image 70
Ajay2707 Avatar answered Oct 09 '22 01:10

Ajay2707


Seems that you're looking for

that.element.style.width
that.element.style.height
etc
like image 12
Kiril Avatar answered Oct 09 '22 01:10

Kiril