1

If there is any way you can measure height of text node without wrapping it?

I've tried useless native method node.style.height, then node.clientHeight, then jQuery method $(node).height()

It gives me javascript error Uncaught TypeError: Cannot read property 'height' of undefined

here is my playground: http://jsfiddle.net/acrashik/F99mm/1/

Sergei Zahharenko
  • 1,514
  • 12
  • 16

1 Answers1

5

You could try getting the bounding box of the TextNode (Using Range, will set height to height of bounding box):

var height = 0;
if (document.createRange) {
    var range = document.createRange();
    range.selectNodeContents(textNode);
    if (range.getBoundingClientRect) {
        var rect = range.getBoundingClientRect();
        if (rect) {
            height = rect.bottom - rect.top;
        }
    }
}

and replace textNode with something like document.body.firstChild;.

Some of code taken from Measure bounding box of text node in Javascript

DEMO

Community
  • 1
  • 1
Cilan
  • 13,101
  • 3
  • 34
  • 51
  • I don't understand why this got a downvote, it works with non-textwrapped text nodes – Cilan Jan 08 '14 at 22:33
  • This seems line a nice answer, I too don't understand the downvote so I will fix it – makeitmorehuman Jan 08 '14 at 22:35
  • @XGreen Thanks, it looks like they un-downvoted :) – Cilan Jan 08 '14 at 22:35
  • 2
    I could see a down-vote because you copied and pasted an answer from another question. This question should have been closed as a duplicate instead, quoting the answer you copied. I don't believe it adds value to Stack Overflow to copy/paste answers... really thought the OP should have searched Stack Overflow first, the answer is obvious with a quick search. – Jasper Jan 08 '14 at 22:38
  • yep, working just fine... but really weird function :) tested http://jsfiddle.net/acrashik/F99mm/5/ – Sergei Zahharenko Jan 08 '14 at 22:40
  • @Jasper You're right, I've just read and it said not to copy *complete* text. However, I think that I changed it *enough...* – Cilan Jan 08 '14 at 22:45
  • @ManofSnow The answer you copied perfectly answered this question. So there's no need to re-write anything, just vote to close the question as a duplicate of the original question. If you add some value to the answer by adding some additional information, that's got value but I don't see any extra information, just less. – Jasper Jan 08 '14 at 22:47
  • @Jasper I just edited my answer and tried to make it more 'original' – Cilan Jan 08 '14 at 22:56