Alexander
Alexander

Reputation: 55

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>

Upvotes: 0

Views: 114

Answers (2)

F. Aumiller
F. Aumiller

Reputation: 124

There is nothing wrong with your JS code. You can see your working code in this Codepen:

https://codepen.io/kmpkt/pen/bvYwpm

But there is a error in your CSS code. CSS values may not be quoted:

background-color: black;

Upvotes: 0

tao
tao

Reputation: 90013

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>

Upvotes: 6

Related Questions