Abhishek Singh
Abhishek Singh

Reputation: 95

Adding HTML by javascript

<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.

Upvotes: 1

Views: 118

Answers (2)

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

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>

Upvotes: 2

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

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

Upvotes: 2

Related Questions