Reputation: 30568
Here is a simple text on a web site, I would like to know what is the My First Heading
length and height in how many pixel and at which position... How can I detect it via javascript? Thanks.
Upvotes: 2
Views: 113
Reputation: 72837
var header = document.getElementById("yourHeadingId");
var w = header.offsetWidth; //Width
var h = header.offsetHeight; //Height
var x = header.offsetLeft; //Top left corner x position.
var y = header.offsetTop; //Top left corner y position.
To change the header's content:
while(header.firstChild) {
header.removeChild(header.firstChild);
}
header.appendChild(document.createTextNode("some new content"));
Upvotes: 1
Reputation: 7887
you can create a temporary h1 element with display: inline style... and than get the offsetWidth. try this:
<script type="text/javascript">
var domId = 'dom-id' + Math.random();
var temp = document.createElement('div');
var body = document.getElementsByTagName('body')[0];
body.appendChild(temp);
var text = document.getElementsByTagName('h1')[0].innerHTML;
var width = null;
var tempH1 = null;
temp.innerHTML = '<h1 style="display: inline" id="' + domId + '">' + text + '</h1>';
tempH1 = document.getElementById(domId);
width = tempH1.offsetWidth;
body.removeChild(temp);
alert(width);
</script>
Upvotes: 0
Reputation: 4197
You can use clientHeight
and clientWidth
to calculate the values. Like
document.getElementById("DOMID").clientWidth
Upvotes: 0
Reputation: 32286
element.offsetWidth
/element.offsetHeight
for the element dimensions.
element.offsetTop
/element.offsetLeft
for the top left corner location (relative to its offsetParent).
Upvotes: 0