1

I created a new div element in JavaScript and I appended some text content. Now I required to get the height of the div which was created in the JavaScript.

Sample code:

const str = 'One of the important elements of a web application is form processing and file uploads. PHP has excellent support for these kind of things which makes it so popular with developers.';

const container = document.createElement('div');
container.style.width = '1020px';
const textContent = document.createTextNode(str)
container.appendChild(textContent);

const width = container. ???   // Should be in number like container.clientHeight
const height = container. ???

The text content will grow based on the topics. How could I get the height and width of the virtual div element without loading in HTML DOM.

Note: I'm not added the div in the real html document. Just created in the javascript and I'm converting the div to PDF for doing this I required the height and width of the div.

Kindly assist me how to do this.

Sreedharan
  • 83
  • 1
  • 3
  • 8
  • If the element hasn't been added to the DOM, how could it have height? It doesn't exist in any visual way. – Turnip Oct 12 '18 at 08:56
  • @Turnip I applied the width, based on the width I required the height. – Sreedharan Oct 12 '18 at 08:58
  • 1
    set an absolute position and huge negative top offset: then append the element to the body, read the `offsetHeight`property and remove the element from the DOM – Fabrizio Calderan Oct 12 '18 at 09:00
  • @fcalderan - Currently I'm doing the same what you said, but it shows the flickering. – Sreedharan Oct 12 '18 at 09:01
  • Then do `visibility:hidden` too. – Mr Lister Oct 12 '18 at 09:02
  • @MrLister - the flickering was happening because some contents are appended in the HTML DOM, if you do the `visibility:hidden`, the content won't visible but the body height will grow and shrink – Sreedharan Oct 12 '18 at 09:05
  • Not if you set an absolute position offscreen, as @fcalderan said. – Mr Lister Oct 12 '18 at 09:09
  • @Turnip - the said question was not meet my expectation. so kindly remove the duplicate tag from this question. – Sreedharan Oct 12 '18 at 09:09
  • Could you reproduce the flickering problem in a fiddle? – Fabrizio Calderan Oct 12 '18 at 09:11
  • @MrLister - I don't know whats the height will come, then how could I decide the negative offset. If its very large content means it will come approx 5000px or more too. then how ? – Sreedharan Oct 12 '18 at 09:11
  • @Sreedharan Explain how your question is not a duplicate of the linked question. Tell us why the answer in that question did not work. – Turnip Oct 12 '18 at 09:13
  • @Turnip - the said question don't have an issue to load the created element in HTML DOM, but in my case I required the output without loading the element in HTML DOM. This is the main difference... – Sreedharan Oct 12 '18 at 10:19

0 Answers0