can not get the width of the html element - javascript

I create an element using js,and I have imported the related css,however I can not get the width of the element,this is the code:
css:
#mainDiv{
position:absolute;
width:500px;
height:500px;
}
js:
var mainDiv=document.createElement("div");
mainDiv.setAttribute("id","mainDiv");
document.body.appendChild(mainDiv);
//now I want to get the width of the 'mainDiv'
var wd=mainDiv.style.width;
console.info(wd);
However the value of the 'wd' is always ''.
I wonder why?
Using the firebug,I found that the width of the 'mainDiv' is 500px.
But why I can not get the value in the js?
I do not want to set the width and height of the 'mainDiv' in the js like:
mainDiv.style.width='500px';
I want to set the size in the css.
Any idea?

try
var wd=mainDiv.clientWidth;

Use mainDiv.offsetWidth .
Hope this helps.

Listen, this is an awful answer, but just use jQuery.
If you did this would be as simple as:
var width = $('#mainDiv').width(); // width has the value 500
Docs: http://api.jquery.com/width/

In order to get the actual width of a DOM element you must use offsetWidth.
From W3Schools:
offsetWidth: Returns the width of an element, including borders and padding if any, but not margins
This example should work:
var mainDiv=document.createElement("div");
mainDiv.setAttribute("id","mainDiv");
document.body.appendChild(mainDiv);
var wd=mainDiv.offsetWidth;
console.info(wd);

It's because the element is not yet rendered. I know it's awful, but you should delay reading the width a bit:
var mainDiv=document.createElement("div");
mainDiv.setAttribute("id","mainDiv");
document.body.appendChild(mainDiv);
setTimeout(100, function() {
console.info(mainDiv.style.width);
});

You cannot get the width because you are trying to get it from the style. Sorry went into train, basically because you are not setting the style element but rather defining a class - JavaScript can't read the value from the element.

Related

How to get height in AngularJS like in JQuery?

I have this jquery snippet below:
$(document).ready(function() {
var height = Math.max($("#one").height(), $("#two").height());
$("#one").height(height);
$("#two").height(height);
});
I want to convert that to AngularJS, but I've been having an issue on actually getting the height. I've tried many different things including offsetHeight and scrollHeight and they all return 0. Is that because I'm using a table? I'm not sure how to do it / if I'm doing it right. Here's kind of an outline of what I've been trying to do so far:
$scope.height = function()
{
var height = window.Math.max(HEIGHT OF MY ELEMENT "firstTable", HEIGHT OF MY ELEMENT "secondTable");
//Now get the height and set it.
};
I'm not sure if I should make this into a directive and put it in my table (where I can access $element) or what.
Thanks in advance
What you're looking for isn't to use AngularJS to get height, but rather use native JavaScript.
Use document.getElementById() to select your element then use .offsetHeight to get the height and finally .style.height to set your height.
Your code would look a little like this:
var elementOne = document.getElementById("one"),
elementTwo = document.getElementById("two"),
height = Math.max(elementOne.offsetHeight, elementTwo.offsetHeight);
elementOne.style.height = height;
elementTwo.style.height = height;
Note that I created variables for each element to avoid repeatedly retrieving the element via document.getElementById() for getting and setting the height.
I would recommand using plain old javascript to do so.
Looks like this works well :
document.getElementById('someDiv').clientHeight;
// clientHeight includes the height and vertical padding.
document.getElementById('someDiv').offsetHeight;
// offsetHeight includes the height, vertical padding, and vertical borders.
document.getElementById('someDiv').scrollHeight;
// scrollHeight includes the height of the contained document (would be greater than just height in case of scrolling), vertical padding, and vertical borders.
Found solution on Stackoverflow : CSS / JavaScript - How do you get the rendered height of an element? so I do not have any merit ;).
jqLite (which is included in Angular) is limited and doesn't offer a function to calculate the height.
Your best options here is to inject the element into controller,
and get the height via:
element[0].offsetHeight;
Demo on plnkr: http://plnkr.co/edit/g45SX4unuCNwlVIUEw4j?p=preview

JavaScript get size of content box

I was using padding to restrict the size of the content-box. I need a way to get the size of the content box width and hight in pixels.
I'm open to work around's like nesting elements, pseudo-elements, trying out something like flex box setups.
However, a vanilla JavaScript way to get these values is the subject of the question.
Example: http://codepen.io/anon/pen/lbzJi
Taken from the answer to a similar question; you can use window.getComputedStyle(element, null).getPropertyValue('css-property'); to obtain the value of a computed CSS property. In your case, you can use this for the properties padding-left, padding-right, padding-top and padding-bottom.
For example, to compute the height of the content box of your "box" div you can do something similar to the following where I assume the padding is specified as an integer (hence the parseInt);
function property(e, p) {
return parseInt(window.getComputedStyle(e, null).getPropertyValue(p));
}
var box = document.getElementById('box');
var paddingTop = property(box, 'padding-top');
var paddingBottom = property(box, 'padding-bottom');
var contentHeight = box.clientHeight - paddingTop - paddingBottom;
Try this using jquery: http://codepen.io/anon/pen/shoun
$(document).ready(function(){
$("pre").append("Total Height = " + ($("#box").height() - parseInt($("#box").css("padding-top"))));
});
Well, you could try:
element.clientHeight
element.clientWidth
-or-
element.offsetWidth
element.offsetHeight
depending on what you want, but we'd need some code to really help you out.

How to use jquery API over html string

context: I have an ajax request which return data structure with an html key.
I would like to wrap this data with a jQuery object to be able to use API like width / height and modify the data before adding it to the DOM.
> $('<div width="220" height="200"></div>').width()
0
So how could I do to get 220 and then modify it ?
I'm using jquery 1.7.2
Edit:
I'm not from the 90's because I use the wrong tag in my example. My need is to change width and height of an iframe for responsive:
> $('<iframe width="220" height="200"></iframe>').width()
0
Elements have no width before they're added to the DOM.
A solution, if you really need to not have it in the DOM, is to add it and then detach it :
var d = $('<div width="220" height="200"></div>');
d.appendTo(document.body);
var w = d.width();
d.detach();
As the screen isn't redrawn until your script ends its task, this operation won't be seen by the user.
But note that without a different style, this won't give you 220. You probably want this :
$('<div style="width:220px;height:200px;"></div>');
Demonstration
You must be from the 90's, because who uses width and height attributes on a div?
There's no width "before adding it to the DOM".
3.
$('<div width="220" height="200"></div>').attr('width')
Use css:
$('<div></div>').css({ 'width': '220px', 'height': '200px'});
This will set the width and height. Since you are setting it, there really is no need to get the width afterwards, right? But you could if needed with width().
EDIT:
Maybe I misunderstood - the question isn't too clear. If you want to get the width of an element then width works, but as mentioned, the element needs to be added to the DOM first.

I can't get a Div's width using element.style.width. Do I have to use element.clientWidth instead?

I think I'm going mad!
I'm starting to write a little exercise for myself where I am going to have some divs that I can drag on the rightborder to increase or decrease the Div width. I also have a container Div that has a set width and I'm going to use this to determine a percentage - basically I'm going to be making some kind of bar-chart / histogram that you can edit.
I'm started writing my code and I thought I'd just make sure I could output the percentage.
Here's the perliminary code....
<style>
#container{width:500px;}
#dragDiv{border:1px solid #000;background-color:pink;width:100px;height:100px;}
</style>
</head>
<body>
<div id="container">
<div id="dragDiv"></div>
</div>
<script>
function dragOneSide(innDiv, outDiv){
if(document.getElementById(innDiv) && document.getElementById(outDiv)){
var iDiv = document.getElementById(innDiv),
oDiv = document.getElementById(outDiv);
// write out the width as a percentage
var iDivWidth = parseInt(iDiv.style.width),
oDivWidth = parseInt(oDiv.style.width);
//alert(document.getElementById("dragDiv").style.width);
iDiv.innerHTML = ((iDivWidth / oDivWidth) * 100);
}
}
window.onload = function(){
dragOneSide("dragDiv", "container");
}
</script>
Now the value in the iDiv was NaN? I found that rather odd. When trying to alert width I was getting a blank, literally an empty string! Rather odd I thought, especially as I wasn't trying to do anything complicated. I used firebug, set a breakpoint and observed the watch window. There was no value for the Div's width. I then put an inline style on the DIV like so...
<div id="container">
<div id="dragDiv" style="width:300px;">Hello World</div>
</div>
and low and behold I was now getting a value for the item! Now I don't like inline styles (who does) however I've never had this problem before and I've been using JavaScript and HTML for years - has anyone got an explaination for this? To retrieve the width not set by CSS do I have to use a different property like clientWidth?
Ps. I haven't included any of the dragging code yet so please don't point that out.
The call to style.width retrieves the style value, which isn't set.
http://jsfiddle.net/EC2HR/
See this example. Yes, you want to use clientWidth in this case.
The simplest way is to use offsetWidth property:
var iDivWidth = parseInt(iDiv.style.offsetWidth),
oDivWidth = parseInt(oDiv.style.offsetWidth);
style.width is a DOM api which returns the width of an element when it's set inline or via the element.style.width = n + "px";
So that it reacts the way you describe it is as designed.
The offsetWidth like ioseb refers to is a DOM api call which returns the amount of horizontal space an element takes up.
Beware of the many inconsistencies between browsers .
PM5544...

Wrong div width when getting it with javascript

I'm trying to get div's width with javascript. Initially div's width is undefined, ie width depends on amount of text on it. Is it possible to get width of this kind of div? I'm trying to do it with following javascript code, but i'm getting width differerent from Chrome console when i'm inspecting div
var mydiv = document.getElementById("error_message");
var curr_width = mydiv.clientWidth;
alert(curr_width);
Thank you for your attention
use offsetWidth
clientWidth is calculated width, offsetWidth is the one in "Chrome inspect element" (i think)
also read the comments :P
While the OP doesn't specify one way or the other, if you happen to have jQuery available, you can always use this:
var curr_width = $('#error_message').width();
I managed to solve the problem! I was trying to create div directly in javascript, without defining div on html body. So inside of tag i've created
<div id="error_message" style="visibility:hidden;"></div>
and it's worked!
Final javascript code is:
document.write("<div id=\"error_message\">Wrong username or password!</div>");
var mydiv = document.getElementById("error_message");
var curr_width = mydiv.offsetWidth;
alert(curr_width);

Categories