1
<head>
<title>untitled</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 0.21" />
<script type="text/javascript">
    var newdiv = document.createElement('div');
    var divIdName = aaa;
    newdiv.setAttribute('id',divIdName);
    newdiv.innerHTML ='adadsdsfd';
    document.body.appendChild(newdiv);
</script>
</head>

<body>
    <div id="aa">
        ddgdf
    </div>
</body>

</html>

I am trying to append a simple html element by javascript but it is not working can someone please point out what is wrong.

4
  • 2
    aaa in divIdName is treated as a variable, but I don't see it defined anywhere. Maybe you wanted "aaa"(a string)? Commented Sep 9, 2013 at 7:06
  • If you look in the error console of your browser, you're likely to see an error saying aaa is undefined. Commented Sep 9, 2013 at 7:07
  • 4
    Besides aaa being undefined you try to access document.body before it's available. Move the script to the end of your document. Commented Sep 9, 2013 at 7:08
  • Uncaught ReferenceError: aaa is not defined is the error.... change it to "aaa"... Your code works then. jsfiddle.net/3Exb6 Commented Sep 9, 2013 at 7:11

2 Answers 2

2

change:

var divIdName = aaa;

to

var divIdName = 'aaa';

as aaa does not look like a variable, it should be string, and add you script before body closing , like

<body>
<script type="text/javascript">
    var newdiv = document.createElement('div');
    var divIdName = 'aaa';
    newdiv.setAttribute('id',divIdName);
    newdiv.innerHTML ='adadsdsfd';
    document.body.appendChild(newdiv);
</script>
</body>

as document.body wont be available to you script placed inside head at the time the script gets executed

Sign up to request clarification or add additional context in comments.

Comments

2

Your id string is not properly quoted -

var divIdName = "aaa";

JavaScript considers aaa as a variable name.

Also, you should move your script to the end of the document. See @pawel's comment.

Final code -

<html>
<head>
    <title>untitled</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta name="generator" content="Geany 0.21" />
</head>

<body>
    <div id="aa">
        ddgdf
    </div>
    <script type="text/javascript">
        var newdiv = document.createElement('div'),
            divIdName = 'aaa';

        newdiv.setAttribute('id', divIdName);
        newdiv.innerHTML ='adadsdsfd';
        document.body.appendChild(newdiv);
    </script>
</body>
</html>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.