Charles Sounder
Charles Sounder

Reputation: 591

How do I get the height of the following statement - angular.element('<div>content</div>')?

How do I get the height of the following statement - angular.element('content') ?

I don't want to place it on the DOM, just get the height. Can I do this? If I have to place it on the DOM first, how would I then get it?

Upvotes: 1

Views: 80

Answers (2)

dfsq
dfsq

Reputation: 193301

I don't want to place it on the DOM, just get the height.

You see, this is a thing, we can't talk about height of the content independently of DOM, because what gives text a dimensions is the fact that it is a part of DOM, with some styles applied, being affected by other elements maybe, etc.

So if you need to get a height of the text you need to do following:

  1. create empty element, e.g. div and append text content in it:

    var div = angular.element('<div>content</div>');
    
  2. append this element into DOM, probably setting styles which makes it "invisible"

    div[0].style.cssText = 'position: absolute; top: -1000px;';
    document.body.appendChild(div[0]);
    
  3. calculate height

    var height = div[0].offsetHeight;  
    
  4. remove element if you don't need it anymore.

    document.body.removeChild(div[0]);
    

Upvotes: 1

Ziga Petek
Ziga Petek

Reputation: 4110

angular.element is just an alias for the jQuery function. So to answer your question, no, you cannot get the height of an element without placing it in the DOM. You can't even get the height of an element, if you add it to the DOM but don't show it.

If you want to get the height of an element, you can simply add it to the DOM, get the height and remove it again. This proccess happens so fast users won't notice it.

Upvotes: 0

Related Questions