DNB5brims
DNB5brims

Reputation: 30568

How can I detect the text size, and position using javascript?

enter image description here

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

Answers (4)

Cerbrus
Cerbrus

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

silly
silly

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

ch4nd4n
ch4nd4n

Reputation: 4197

You can use clientHeight and clientWidth to calculate the values. Like

document.getElementById("DOMID").clientWidth

Upvotes: 0

Alexander Pavlov
Alexander Pavlov

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

Related Questions