Question

While coding an HTML5 Page (PHP included) I noticed that createElement() stops working when the doctype is switched to html5

<!DOCTYPE html>

The code is pretty standard element creation with Javascript:

function Rhit(){
        var Hit=document.createElement('div');
        if(Hit){
            alert('Hit assigned.');
            Hit.setAttribute('id','Hits');
            if(document.body.appendChild(Hit)){
                alert('Hit transferred to body; setting styles.');
                Hit.style.width='400';
                Hit.style.height='400';
                Hit.style.position='absolute';
                Hit.style.right='0';
                Hit.style.top='0';
                Hit.style.backgroundColor='#777777';
            }
        }
        else{
            alert('Create Element Error, please debug.');
        }

    }

(I've debugged it a bit under the html5 doc type... sort of.) The alerts pop up, but no div tags are drawn under the html5 doctype. (Works fine with regular html super sandbox mode)

Am I missing something?

(Also, all code shows up in browser source.) It seems like the code is being parsed but not drawn?

EDIT: Here's a full demo. In the meantime I'm added those comments in:

<html> <!--if !html5 document draws.-->
<head> 
 <script>
     function proc(){
        var foo=document.createElement('div');

        //Test foo creation.
        if(foo){
            alert('Hit assigned.'); 
            foo.setAttribute('id','Hits');

            //test foo location assignment.
            if(document.body.appendChild(foo)){

                alert('Hit transferred to body; setting styles.'); 

                //Set all other stuff.
                foo.style.width='400';
                foo.style.height='400';
                foo.style.position='absolute';
                foo.style.right='0';
                foo.style.top='0';
                foo.style.backgroundColor='#777777';
            }
        }
        //If failed, all is lost.
        else{
            alert('Create Element Error, please debug.');
        }

    }
 </script>
</head>
<title></title>
<body>
    <script>
    proc(); //Run function.
    document.write('Javascript Running...');
    //Failsafe (for IDE's who don't care if your eyes hurt and insist
    //that java has an error "somewhere".)
    </script>   
</body>

Was it helpful?

Solution

Your height and width are defined incorrectly and are therefore (iirc) being assigned 0.

These CSS style rules require values be percent or pixels. So:

Hit.style.width = '400px';
Hit.style.height = '400px';

should give the element some dimensions, and let it be seen.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top