get height from style attribute - javascript

Is there a way to get the height from a style attribute on a div?
<div style="height:100px;"></div>
I can't use .height() as this will just return me the current height of the element - I need to check if the style has been set and then get that height if it has

The easiest way is to go straight to the style property:
var heightStyleValue = $("selector for your element")[0].style.height;
You don't want to use jQuery's css function because that will give you the calculated height, not the value from the style object.

Use css() in jquery
$('div').css('height');

I can't use .height() as this will just return me the current height of the element (...)
How is this possible? Unless you're using some !important statements (which you should avoid), the style attribute has higher specificity than anything else in your CSS. Therefore, the height returned by height() should be the same, unless it's constrained by some other container.
However in order to achieve what you want to do, you need to do 2 things:
Assign an ID to your div so you can target it in your Javascript
Use:
document.getElementById("yourID").style.height;

You cannot use elem.style.height because the named values of style have default values.
If you actually want to know which style parameters has been set, treat style as an array.
Vanilla:
// get style attributes that were actually set on the element
function getStyle(elem,prop) {
var actuallySetStyles = {};
for (var i = 0; i < elem.style.length; i++) {
var key = elem.style[i];
if (prop == key)
return elem.style[key];
actuallySetStyles[key] = elem.style[key];
}
if (!prop)
return actuallySetStyles;
}
console.log(getStyle(elem,'height'));
console.log(getStyle(elem));
jQuery:
jQuery.fn.extend({
// get style attributes that were set on the first element of the jQuery object
getStyle: function (prop) {
var elem = this[0];
var actuallySetStyles = {};
for (var i = 0; i < elem.style.length; i++) {
var key = elem.style[i];
if (prop == key)
return elem.style[key];
actuallySetStyles[key] = elem.style[key];
}
if (!prop)
return actuallySetStyles;
}
}
console.log(jQuery(elem).getStyle('height'));
console.log(jQuery(elem).getStyle());

Related

Why is my js returning an empty string when I check the background colour of an element? [duplicate]

I am looking for a way to retrieve the style from an element that has a style set upon it by the style tag.
<style>
#box {width: 100px;}
</style>
In the body
<div id="box"></div>
I'm looking for straight javascript without the use of libraries.
I tried the following, but keep receiving blanks:
alert (document.getElementById("box").style.width);
alert (document.getElementById("box").style.getPropertyValue("width"));
I noticed that I'm only able to use the above if I have set the style using javascript, but unable to with the style tags.
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.
I believe you are now able to use Window.getComputedStyle()
Documentation MDN
var style = window.getComputedStyle(element[, pseudoElt]);
Example to get width of an element:
window.getComputedStyle(document.querySelector('#mainbar')).width
In jQuery, you can do alert($("#theid").css("width")).
-- if you haven't taken a look at jQuery, I highly recommend it; it makes many simple javascript tasks effortless.
Update
for the record, this post is 5 years old. The web has developed, moved on, etc. There are ways to do this with Plain Old Javascript, which is better.
Use getComputedStyle function, Computed style contains all the CSS properties set to an element. Even if do not set a property to an element. You will still find that property in the computed styles.
Example:
<style>
#Body_element {
color: green;
}
</style>
<body id="Body_element">
<script>
alert(getComputedStyle(Body_element).color)
</script>
</body>
This is a helper function if you want to get multiple style rules from the same element.
You pass it the element and the styles you want as arguments, and it will return their values
const convertRestArgsIntoStylesArr = ([...args]) => {
return args.slice(1);
}
const getStyles = function () {
const args = [...arguments];
const [element] = args;
let stylesProps = [...args][1] instanceof Array ? args[1] : convertRestArgsIntoStylesArr(args);
const styles = window.getComputedStyle(element);
const stylesObj = stylesProps.reduce((acc, v) => {
acc[v] = styles.getPropertyValue(v);
return acc;
}, {});
return stylesObj;
};
Now, you can use this function like this:
const styles = getStyles(document.body, "height", "width");
OR
const styles = getStyles(document.body, ["height", "width"]);

JavaScript Object Literal and jQuery $(classes)

I have an object that contains a list of browser widths
breakpoints {
smallMobile: 0,
mobile: 480,
tablet: 672,
desktop: 868,
largeDesktop: 1050
}
I want to add a class to the body of the document based on whether the browser width falls between two values in the breakpoints object.
What I have so far
var key;
for (key in breakpoints) {
if (breakpoints.hasOwnProperty(key))
if (winWidth >= breakpoints[key]) {
$('body').removeClass().addClass(key);
} else {
$('body').removeClass(key);
}
}
}
Now this works, however it also removes ALL classes from the body. Instead I would like to add only one class, and not have to remove anything unless the breakpoint no longer matches.
I'm sure there has to be a way. Any help would be appreciated :)
EDIT
Current output at various widths
>= 1050: <body class="smallMobile mobile tablet desktop largeDesktop">
>= 868: <body class="smallMobile mobile tablet desktop">
>= 672: <body class="smallMobile mobile tablet">
Ideal output
>= 1050: <body class="largeDesktop">
>= 868: <body class="desktop">
>= 672: <body class="tablet">
(For the record I use Media Queries, but I need access to classnames for an edge case)
I've slightly modified your code and saved the class thats the highest applicable one. Then I remove every class and apply the applicable one.
// create a variable to store the only class you want to apply
var apply = "";
for (var key in breakpoints) {
// keep overwriting the apply var if the new key is applicable
if (winWidth >= breakpoints[key]) {
apply = key;
}
// remove any existing classes with that keyname
$('body').removeClass(key);
}
// add the key to the body as a class
$('body').addClass(apply);
Also, you can remove breakpoints.hasOwnProperty(key) as the for-loop only loops through keys that actually exist anyway, so you are doing an unnecessary check.
Update
At #juvian's note, I'll add a way to make sure that the order in which you make your object makes no difference:
var apply = "";
var check = 0;
for (var key in breakpoints) {
// Also check if the value is higher than the last set value
if (winWidth >= breakpoints[key] && breakpoints[key] >= check) {
apply = key;
check = breakpoints[key];
}
$('body').removeClass(key);
}
$('body').addClass(apply);
It's because you're using removeClass() without any parameter in it.
If a class name is included as a parameter, then only that class will
be removed from the set of matched elements. If no class names are
specified in the parameter, all classes will be removed.
Source: http://api.jquery.com/removeClass/
So, you should find the right class to remove and then call this function with a param.
Consider to store your breakpoints in sorted array instead of map:
var dimensions = [];
for (var key in breakpoints) {
dimensions.push({ name: key, width: breakpoints[key] })
}
dimensions.sort(function(a, b) { return b.width - a.width });
Now dimensions is
[
{"name":"largeDesktop","width":1050},
{"name":"desktop","width":868},
{"name":"tablet","width":672},
{"name":"mobile","width":480},
{"name":"smallMobile","width":0}
]
Of course you can hardcode it in this structure and not grep/sort each time.
Finally, find highest width with
for (var i = 0; i < dimensions.length; i++) {
if (winWidth >= dimensions[i].width) {
$("body").addClass(dimensions[i].name);
break;
}
}
However, if you want to create responsive layout, media queries is the way to go. Media queries also will take windows resize/orientation change events into account.
Here is a way you can get the one that matches with the highest value:
var wid = 868;
var max = 0;
var size = null;
Object.keys(breakpoints).map(function(a){
size = wid >= breakpoints[a] ? a : size;
max = wid >= breakpoints[a] ? Math.max(max,breakpoints[a]) : max;
})
console.log(max, size) // 868, 'desktop'
if you use .removeClass() without parameter then all class on selected element will remove as like prabu said, but if you want, i give some example so you will not confused how to remove class if window width less than breakpoints
var key;
for (key in breakpoints) {
if (breakpoints.hasOwnProperty(key)) {
$("body").addClass(key);
if (winWidth<breakpoints[key]) {
$("body").removeClass(key);
}
}
}

CSS/JavaScript: Make element top-most z-index/top-most modal element

I would like to make an element (e.g. a <div>) be the top-most layer on the page.
My assumption is that the only way I can do this is to specify that the element has a style="z-index:" value that is the maximum the browser allows (int32?).
Is this correct?
Instead, would it be possible to somehow get the element's z-index whose is highest, and make this <div>'s z-index the [highest element's value] + 1? For example:
$myDiv.css("z-index", $(document.body).highestZIndex() + 1);
How do modal JavaScript "windows" work?
Here's how to do it :
var elements = document.getElementsByTagName("*");
var highest_index = 0;
for (var i = 0; i < elements.length - 1; i++) {
if (parseInt(elements[i].style.zIndex) > highest_index) {
highest_index = parseInt(elements[i].style.zIndex;
}
}
highest_index now contains the highest z-index on the page... just add 1 to that value and apply it wherever you want. You can apply it like so :
your_element.style.zIndex = highest_index + 1;
Here's another way of achieving the same thing using jQuery :
var highest_index = 0;
$("[z-index]").each(function() {
if ($(this).attr("z-index") > highest_index) {
highest_index = $(this).attr("z-index");
}
});
Again, same way to apply the new index to an element :
$("your_element").attr("z-index", highest_index + 1);
What about stacking context? It is not always true that: On a document highest z-index will be on top. See: http://philipwalton.com/articles/what-no-one-told-you-about-z-index/. If you do not take stacking context into account, setting a billion may not be enough to make your element on the top-most.
http://abcoder.com/javascript/a-better-process-to-find-maximum-z-index-within-a-page/ -> find the max z-index and assign +1 to it.
Sheavi's jQuery solution doesn't work because z-index is a css style, not an attribute.
Try this instead:
raiseToHighestZindex = function(elem) {
var highest_index = 0;
$("*").each(function() {
var cur_zindex= $(this).css("z-index");
if (cur_zindex > highest_index) {
highest_index = cur_zindex;
$(elem).css("z-index", cur_zindex + 1);
}
});
return highest_index;
};
Return value may not be what you expect due to Javascript's async nature, but calling the function on any element will work fine.

Get a CSS value from external style sheet with Javascript/jQuery

Is it possible to get a value from the external CSS of a page if the element that the style refers to has not been generated yet? (the element is to be generated dynamically).
The jQuery method I've seen is $('element').css('property');, but this relies on element being on the page. Is there a way of finding out what the property is set to within the CSS rather than the computed style of an element?
Will I have to do something ugly like add a hidden copy of the element to my page so that I can access its style attributes?
With jQuery:
// Scoping function just to avoid creating a global
(function() {
var $p = $("<p></p>").hide().appendTo("body");
console.log($p.css("color"));
$p.remove();
})();
p {color: blue}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Using the DOM directly:
// Scoping function just to avoid creating a global
(function() {
var p = document.createElement('p');
document.body.appendChild(p);
console.log(getComputedStyle(p).color);
document.body.removeChild(p);
})();
p {color: blue}
Note: In both cases, if you're loading external style sheets, you'll want to wait for them to load in order to see their effect on the element. Neither jQuery's ready nor the DOM's DOMContentLoaded event does that, you'd have to ensure it by watching for them to load.
Normally you should be let the browser apply all the rules and then ask the browser for the results, but for the rare case where you really need to get the value out of the style sheet you can use this: (JSFiddle)
function getStyleSheetPropertyValue(selectorText, propertyName) {
// search backwards because the last match is more likely the right one
for (var s= document.styleSheets.length - 1; s >= 0; s--) {
var cssRules = document.styleSheets[s].cssRules ||
document.styleSheets[s].rules || []; // IE support
for (var c=0; c < cssRules.length; c++) {
if (cssRules[c].selectorText === selectorText)
return cssRules[c].style[propertyName];
}
}
return null;
}
alert(getStyleSheetPropertyValue("p", "color"));
Note that this is pretty fragile, as you have to supply the full selector text that matches the rule you are looking up (it is not parsed) and it does not handle duplicate entries or any kind of precedence rules. It's hard for me to think of a case when using this would be a good idea, but here it is just as an example.
In response to Karim79, I just thought I'd toss out my function version of that answer. I've had to do it several times so this is what I wrote:
function getClassStyles(parentElem, selector, style){
elemstr = '<div '+ selector +'></div>';
var $elem = $(elemstr).hide().appendTo(parentElem);
val = $elem.css(style);
$elem.remove();
return val;
}
val = getClassStyles('.container:first', 'class="title"', 'margin-top');
console.warn(val);
This example assumes you have and element with class="container" and you're looking for the margin-top style of the title class in that element. Of course change up to fit your needs.
In the stylesheet:
.container .title{ margin-top:num; }
Let me know what you think - Would you modify it, and if so how? Thanks!
I have written a helper function that accepts an object with the css attributes to be retrieved from the given css class and fills in the actual css attribute values.
Example is included.
function getStyleSheetValues(colScheme) {
var tags='';
var obj= colScheme;
// enumerate css classes from object
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && typeof obj[prop]=="object") {
tags+= '<span class="'+prop+'"></span>';
}
}
// generate an object that uses the given classes
tags= $('<div>'+tags+'</div>').hide().appendTo("body");
// read the class properties from the generated object
var idx= 0;
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && typeof obj[prop]=="object") {
var nobj= obj[prop];
for (var nprop in nobj) {
if (nobj.hasOwnProperty(nprop) && typeof(nobj[nprop])=="string") {
nobj[nprop]= tags.find("span:eq("+idx+")").css(nobj[nprop]);
}
}
idx++;
}
}
tags.remove();
}
// build an object with css class names where each class name contains one
// or more properties with an arbitrary name and the css attribute name as its value.
// This value will be replaced by the actual css value for the respective class.
var colorScheme= { chart_wall: {wallColor:'background-color',wallGrid:'color'}, chart_line1: { color:'color'} };
$(document).ready(function() {
getStyleSheetValues(colorScheme);
// debug: write the property values to the console;
if (window.console) {
var obj= colorScheme;
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && typeof obj[prop]=="object") {
var nobj= obj[prop];
for (var nprop in nobj) {
if (nobj.hasOwnProperty(nprop)) {
console.log(prop+'.'+nprop +':'+ nobj[nprop]);
}
}
}
}
// example of how to read an individual css attribute value
console.log('css value for chart_wall.wallGrid: '+colorScheme.chart_wall.wallGrid);
}
});
I wrote this js function, seems to be working for nested classes as well:
usage:
var style = get_css_property('.container-class .sub-container-class .child-class', 'margin');
console.log('style');
function get_css_property(class_name, property_name){
class_names = class_name.split(/\s+/);
var container = false;
var child_element = false;
for (var i = class_names.length - 1; i >= 0; i--) {
if(class_names[i].startsWith('.'))
class_names[i] = class_names[i].substring(1);
var new_element = $.parseHTML('<div class="' + class_names[i] + '"></div>');
if(!child_element)
child_element = new_element;
if(container)
$(new_element).append(container);
container = new_element;
}
$(container).hide().appendTo('body');
var style = $(child_element).css(property_name);
$(container).remove();
return style;
}

Get all css styles for a DOM element (a la Firebug)

For a DOM element, how to I get all styles specified in css for a particular element? Is it a case of iterating over all css style names?
Or is there a more elegant way? How does Firebug do it?
Thanks
You should be able to get it with getComputedStyle:
var css = window.getComputedStyle(element);
for (var i=0; i<css.length; i++) {
console.log(css[i] +'='+css.getPropertyValue(""+css[i]))
}
However, this method returns computed style meaning that it will perform some computation and convert your values in px. For example if you have a line-height of 1.2 then it will be returned as 57.6px instead of 1.2
Preveous solutions mangle the styles as they are modified before expanded.
Also you get a lot of default styles.
my solution strips the default styles and keeps the cascading styles through the elements.
Run in console and copy the element you want from the Elements view. (tested in chrome)
function setStyle(theElement) {
var els = theElement.children;
for(var i = 0, maxi = els.length; i < maxi; i++)
{
setStyle(els[i]);
var defaultElem = document.createElement(els[i].nodeName)
var child = document.body.appendChild(defaultElem);
var defaultsStyles = window.getComputedStyle(defaultElem,null);
var computed = window.getComputedStyle(els[i],null).cssText;
for(var j = 0, maxj = defaultsStyles.length; j < maxj; j++)
{
var defaultStyle = defaultsStyles[j] + ": " + defaultsStyles.getPropertyValue(""+defaultsStyles[j]) + ";"
if(computed.startsWith(defaultStyle)) {
computed = computed.substring(defaultStyle.length);
} else {
computed = computed.replace(" " + defaultStyle, "");
}
}
child.remove();
els[i].setAttribute("style", computed);
}
}
setStyle(document.getElementsByTagName("body")[0]);
console.log("DONE");
You can iterate through all of the CSS styles for an element like this:
var myElement = document.getElementById('someId');
var myElementStyle = myElement.style;
for(var i in myElementStyle){
// if it's not a number-index, print it out.
if(/^[\d]+/.exec(i) == null){
console.log("Style %s = %s", i, myElementStyle[i]);
/*
* Do other stuff here...
*/
}
}
For a DOM element, how to I get all
styles specified in css for a
particular element? Is it a case of
iterating over all css style names?
Yes, it is.
Or is there a more elegant way?
I don't know about more elegant (elegance is pretty high on the subjective scale), but it would certainly be shorter and sweeter if you made use of a library such as jQuery, here's a solution someone coded to answer another question:
How Can I Get List Of All Element CSS Attributes with jQuery?
How does Firebug do it?
I have no idea.

Categories