Offsetwidth by a new HTML Document

295 views Asked by At

I want to create a new html document with javascript. There in the body i want create a div (display: inline) and in there a p tag. Then i put in the p tag (innerHTML) a String (titleTagString). Now i want know, which is offsetwidth the div has. The chrome console say 0 ... Where is the failure? Thanks!

function titleTagTester(titleTagString) {
  //Create new document
  newDoc = document.implementation.createHTMLDocument('titleTagTester.html');
  //Create var body from document
  var body = newDoc.getElementsByTagName('body');
  
  //Create div element with style and add to body of document  
  newDoc.body.innerHTML += '<div style="width:600px" display="inline" id="divId"></div>';
  
  //Create p element with style and add to div of body of document  
  newDoc.getElementById('divId').innerHTML += '<p style="color:#1a0dab" "font-family:arial" font-size:18px;">' + titleTagString + '</p>';
  
  //getwidth of div
  return newDoc.getElementById("divId").offsetWidth;
}

1

There are 1 answers

0
Siddharth Srinivasan On

I made a HTML document with the script embedded within it such that the script manipulates the same document DOM:

<!DOCTYPE html>
<html>
<head>
<title>temp</title>
</head>
<body>
<h1>Domething</h1>
</body>
<script type="text/javascript">
function titleTagTester(titleTagString) {
  var body = document.getElementsByTagName('body');
  
  //Create div element with style and add to body of document  
  document.body.innerHTML += '<div style="width:600px" display="inline" id="divId"></div>';
  
  //Create p element with style and add to div of body of document  
  document.getElementById('divId').innerHTML += '<p style="color:#1a0dab" "font-family:arial" font-size:18px;">' + titleTagString + '</p>';
  
  //getwidth of div
  return document.getElementById("divId").offsetWidth;
}
console.log(titleTagTester('temp'))
</script>
</html>

For this web document, the console says 600. This is not a good answer to your question since the intention is to create a new document and obtain the required offset from that document. However, the createHTMLDocument in your case doesn't seem to work and is found out by printing the value of newDoc.readyState, which turns out to be uninitialized, and this in turn is responsible for the offsetwidth value as 0. One way to correct this is to call the function with an onload event handler instead of calling the function directly within the script tag (Ex. <body onload="titleTagTester('tempString')">).