Some_ Person
Some_ Person

Reputation: 75

I'm create div via js, but it doesn't appear on my page

In my JS code, I created a new div. I checked, and it isn't null, but it doesn't appear on my page.

This is my code:

  snake.push(document.createElement('div'));
  snake[0].style.width = '1000px';
  snake[0].style.height = '1000px';
  snake[0].style.background = 'red';
  snake[0].style.color = 'blue';
  console.log(snake[0]);

I used console.log() to check, that snake[0] isn't null

snake is empty list: let snake = [];

Why snake[0] doesn't appear on the page?

Upvotes: 0

Views: 188

Answers (2)

AdamKniec
AdamKniec

Reputation: 1717

You've created the element but you did not attach it to the DOM. Take a look here: https://dev.to/desoga/7-javascript-methods-that-aids-dom-manipulation-kkj

It's a list of helpful methods that you can use while working on DOM manipulation.

Upvotes: 2

Zevan
Zevan

Reputation: 10235

As others have commented, what you are looking for is appendChild. This method enables DOM nodes to be added as children of other DOM nodes. It is very closely related to the composite pattern.

var snake = [];
snake.push(document.createElement('div'));
snake[0].style.width = '1000px';
snake[0].style.height = '1000px';
snake[0].style.background = 'red';
snake[0].style.color = 'blue';
console.log(snake[0]);
document.body.appendChild(snake[0]);

In this case I've appended snake[0] to the body.

Upvotes: 2

Related Questions