2

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.

6
  • Well, I can use it, but prefer a prue javascript solution. Commented Nov 26, 2012 at 13:50
  • With jQuery it is easy. offset() return the absolute position referred to the document, while .css("width") and .css("height") the dimension in px. Commented Nov 26, 2012 at 13:51
  • you could use .position() with jQuery returns an object with left top of the elemnt Commented Nov 26, 2012 at 13:52
  • @SantiagoRebella that returns the coordinate referred to the sole container, not to the document Commented Nov 26, 2012 at 13:57
  • @JeanValjean but if the <h1> is not in any container does not returns top left from document? I was sure than yes :( Commented Nov 26, 2012 at 14:00

4 Answers 4

1
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"));
Sign up to request clarification or add additional context in comments.

2 Comments

If I would like to have My First only, is this possible to do so ?
You could set the text to "My First", then get the values like I posted, and set the text back. Other than that, it's not possible.
0

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>

Comments

0

element.offsetWidth/element.offsetHeight for the element dimensions. element.offsetTop/element.offsetLeft for the top left corner location (relative to its offsetParent).

Comments

0

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

document.getElementById("DOMID").clientWidth

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.