Javascript - Get the width of an undefined element - javascript

I have a div element, that has no defined width or height. It holds other elements, and molds on their size.
I need to get the final size of the div, without being able to check the sizes of the elements inside of it (dynamic elements).
I tried parsing all the properties of the object, but found nothing, all were "undefined".
Any thoughts?
Many thanks
Later edit:
I have
<div id="xxx" style="position:relative;">
aaaa
</div>
I tried:
var a = mydiv.style.width;
But it did not work.
I also tried:
var getKeys = function (obj) {
var keys = [];
for(var key in obj){
document.write(key+"="+obj.key+"<br>");
}
return keys;
}
getKeys(mydiv.style);
To show all the properties, but none had any info.
The jQuery solution works perfectly, but getComputedStyle was what I was looking for, as I can't use jquery here.
Sorry for the short information.

Based on no information whatsoever about what you were doing, I'd suggest that you should (if possible) use the window.getComputedStyle() approach, which finds the properties of an object as rendered by the browser:
var elem = document.getElementById('elemId'),
properties = window.getComputedStyle(elem, null),
height = properties.height,
width = properties.width;
If you have jQuery available, then you can simply use the width() and height() (or outerWidth()/outerHeight()) methods:
var height = $('#elem').height(),
width = $('#elem').width();

You don't give a whole lot of information. I'd suggest you edit your post with the actual code you tried using.
However, with JQuery:
$(DOMElement).width() //-- Element width.
$(DOMElement).innerWidth() //-- Element width + padding.
$(DOMElement).outerWidth() //-- Element width + padding & border.
$(DOMElement).outerWidth(true) //-- Element width + padding, border, and margin.

$('div').width() will return the width...

Related

How to get full height (including margins) with window.getComputedStyle()?

I am trying to get the full height of a JSX element in ReactJS using window.getComputedStyle, however I'd like to get the full value, height+margin, but I couldn't find a way.
When I use only height I don't get the margin value.
window.getComputedStyle(productsContainerRef.current).height
I know I can get both values separetely and sum them, but is there a straightforward way to do that?
I am getting the element using a ref, so, it wouldn't be possible to use the event to aim the target element and get outerHeight.
Is there a way to do that using getComputedStyle?
One option is to add the margins to the refs current height.
Example:
const outerHeight = (el) => {
var height = el.offsetHeight;
var style = window.getComputedStyle(el);
height += parseInt(style.marginTop) + parseInt(style.marginBottom);
return height;
};

Get Actual CSS Property of element if it dynamically added "!important"

I have a Element with the id="somID";
For Example:
Html:
<div id='somID' ></div>
Css :
#somID{ width:500px;height:500px}
and i have a class named : maximize.
So,
.maximize{width:100% !important; height:100% !important; }
Now dynamically i added the class .maximize to my div #somID
And after that i wanna get the width and height of my #somID by calling with its ID like,
$('#somID').width() or .height()
but i want to take the actual height of element that is defined in its ID but i get the .maximize in result not the height or width that is in #somID.
Any buddy have any idea ? That how to retrieve the height of div#somID if it contains .maximize ??
The problem is, there can be many, many selectors that are applied to a given element, with different specificities. There is no API that allows you to request a property from a selector in CSS - it simply wouldn't make much sense.
Having said that, you can create a hack to solve that issue:
function getOriginalDimensions(id) {
var $a = $("<div>", {id:id});
$("body").append($a);
var width = $a.width();
var height = $a.height();
$a.remove();
return {width:width, height:height};
}
console.log(getOriginalDimensions("somID")); // returns {width:500, height:500}
The above works with your example HTML and CSS.
JSFiddle
This basically creates an element with the same ID, appends it to the body, reads the dimensions and deletes it immediately. This is necessary because the div will have no size if it is just kept as a document fragment and not added to the DOM, because the CSS will not get applied.
In theory you could expand this function to make it work with other selectors.
However bear in mind this is a nasty hack and you should reconsider your approach.
A. Make your measurements and save them as .data attributes of the element :
var $el = $('#somID');
$el.data('original_dims', {
height: $el.height(),
width: $el.width()
}
B. Add class that changes the dimensions of the element :
$el.addClass('maximise');
C. Retrive the original dimensions whenever they are needed
var h = $el.data('original_dims').height;
var w = $el.data('original_dims').width;

How to find element with biggest z-Index?

I have a lot of dynamic created elements, anytime it getting z-Index++, so that the latest element is anytime on top. When one other of them will be clicked, he get his z-Index max+1. So i need to get the element, that is on top, how can i do it?
Native JS Only please. Thank you
Don't try to find it - you would need to iterate all your DOM. As you are creating them dynamically, just save a reference to it and update it each time. Or just store the current highest z-index value in a max variable.
http://jsfiddle.net/h4ets/
assuming you are only applying z-index in the style attribute
var elems = document.body.getElementsByTagName("*");
var largest;
var check = 0;
for(i=0;i<elems.length;i++){
if(elems[i].style.zIndex > check){
check = elems[i].style.zIndex;
largest = elems[i];
}
}
// largest is the element
// check is the z-index value of the element with largest z-index
getting the computed style of elements seems to be an issue in webkit browsers such as chrome, and safari as it returns auto, this is a major isssue as chrome especially now is a popular and widely used browser. so for now i would suggest if you want to do this apply the z-index in a style attribute until the bug is fixed
This a best solution
$(function(){
var maxZ = Math.max.apply(null,$.map($('body > *'), function(e,n){
if($(e).css('position')=='absolute')
return parseInt($(e).css('z-index'))||1 ;
})
);
alert(maxZ);
});

Calculating html element (div) width with javascript/dojo?

Normally when you have a div created in html. You can check its width with offsetWidth or style.width (if declared). However if the innerHTML is changed such that the width of the div is also change, neither of those functions work (not sure, but they haven't in my cases).
some code:
var div = document.createElement("div");
div.innerHtml = "asdfasdfasdfasdfsdfasdfasdfad";
alert(div.style.width); // this is nothing
alert(div.offsetWidth); // this is 0
How do you get the width of the div above?
I realize this is an old question, but for the many people landing here from google I'll provide it.
This is the way to do it in dojo 1.7+. With the geometry module you can get and set the width of the content (not including padding or border). This ignores box-sizing.
require(['dojo/dom-geometry'], function(domGeom) {
var myDivNode = dojo.query('div')[0];
var contentBox = domGeom.getContentBox(myDivNode);
alert(contentBox.w);
// This is how to set width/height
domGeom.setContentSize(myDivNode, {w: 100, h: 100});
});
Source: https://dojotoolkit.org/reference-guide/1.7/dojo/contentBox.html
you can't get width value of element that wasn't appended to document.
so you should append it to page, than you can get width,
here is a working demo

js style properties returns blank

I am trying to receive the original CSS width value of an object using JavaScript. However, if I use:
var originalWidth = document.getElementById(<idOfObject>).style.width;
It always returns blank. I've also noticed that any property I access using this syntax will return blank. I know for sure that the given element exists, since
alert(document.getElementById(<idOfObject>));
does shows me the right object.
Can anyone help me to solve this problem?
You probably try to get the value which was set in stylesheet, not directly like this:
document.getElementById(<idOfObject>).style.width = '100px';
If you want to get the width of the element you can use innerWidth property:
var width = document.getElementById(<idOfObject>).offsetWidth;
None of the previous answers were right.
The property you are looking for is clientWidth, but not in "style"
document.getElementById('idOfObject').clientWidth;
That will work both on "width" set with external css, style seccion or even inline style="width:80px"
General note: don't use <div width="500"> as it has no effect
The mentioned offsetWidth is the second best choice, but it does not return the exact width set in css, but that width plus border width
Other options like innerWidth that works with window object didn't work for me on divs.
This bizarre issue of realizing style.width not working properly, wasted 2 hours of my precious time :-), hope this answer shorts that time for anyone else in the future.
<div style="width:10%" id="mydiv" >
OR
<div style="width:10px" id="mydiv" >
var mydiv = document.getElementById("mydiv");
var curr_width = mydiv.style.width;
alert(curr_width);
This works for me
I tried it and I can get the value
http://jsfiddle.net/xyd95/
Well, unless the width has no unit
http://jsfiddle.net/xyd95/1/
I believe this will work
function getWidth()
{
x = document.getElementById(<idOfObject>)
return x.offsetWidth;
}

Categories

Resources