Search code examples
javascripthtmlappendchild

creating elements inside of DOM with JS


I'm a beginner so I'm sorry for a stupid question. The matter is I can't add div "title" inside of div "app" using JS. Help me please.

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset = "utf-8">
        <meta name = "description" content = "Field v.1">
        <title> Field v.1 </title>

        <style>
        .app{
            background-color: 'black';
        }
        .title{
            background-color: 'green';
        }
        </style>
    </head>

    <body>
        <div class = "app">
        </div>

        <script>
            var app = document.querySelector('.app')
            var title = document.createElement('div')
            title.className = 'title'
            title.innerHTML = "BREAKING NEWS"
            app.appendChild(title);
        </script>
    </body>
</html>


Solution

  • The JavaScript works perfectly. Here's the result of your JS:

    <div class="app">
      <div class="title">BREAKING NEWS</div>
    </div>
    

    However, there's a small problem with your CSS. Do not quote CSS values!. It should be:

    .app{
        background-color: black;
    }
    .title{
        background-color: green;
    }
    

    <!DOCTYPE HTML>
    <html>
    	<head>
    		<meta charset = "utf-8">
    		<meta name = "description" content = "Field v.1">
    		<title> Field v.1 </title>
    
    		<style>
    		.app{
    			background-color: black;
    		}
    		.title{
    			background-color: green;
    		}
    		</style>
    	</head>
    
    	<body>
    		<div class = "app">
    		</div>
    
    		<script>
    			var app = document.querySelector('.app')
    			var title = document.createElement('div')
    			title.className = 'title'
    			title.innerHTML = "BREAKING NEWS"
    			app.appendChild(title);
    		</script>
    	</body>
    </html>