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;
}
I made a HTML document with the script embedded within it such that the script manipulates the same document DOM:
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
createHTMLDocumentin your case doesn't seem to work and is found out by printing the value ofnewDoc.readyState, which turns out to be uninitialized, and this in turn is responsible for the offsetwidth value as0. 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')">).