Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

Tags:

javascript

dom

I want to create new divs as the page loads. These divs will appear as an ordered group which changes depending upon external data from a JSON file. I will need to do this with a for loop because there are over 100 divs needed.

So, I need to be able to change each created div in regards to height, width, top/left and so on. Yet, document.getElementById("created_div").style.whatever does nothing, I can't even see a single new div appear. I've set the new divs height/width to 500px, background to "red", and so on, but no new divs are definitely appearing.

What am I doing wrong?

like image 664
Erik Nelson Avatar asked Dec 30 '12 21:12

Erik Nelson


People also ask

What is a dynamic div?

Dynamic Divs are the connecting elements between your HTML content and STML pages. Generally speaking, your STML pages will contain several Dynamic Divs. These drop-zones allow you to easily drop HTML content into the page itself.

Can you append a div to a div?

HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code.


1 Answers

  • Creation var div = document.createElement('div');
  • Addition document.body.appendChild(div);
  • Style manipulation
    • Positioning div.style.left = '32px'; div.style.top = '-16px';
    • Classes div.className = 'ui-modal';
  • Modification
    • ID div.id = 'test';
    • contents (using HTML) div.innerHTML = '<span class="msg">Hello world.</span>';
    • contents (using text) div.textContent = 'Hello world.';
  • Removal div.parentNode.removeChild(div);
  • Accessing
    • by ID div = document.getElementById('test');
    • by tags array = document.getElementsByTagName('div');
    • by class array = document.getElementsByClassName('ui-modal');
    • by CSS selector (single) div = document.querySelector('div #test .ui-modal');
    • by CSS selector (multi) array = document.querySelectorAll('div');
  • Relations (text nodes included)
    • children node = div.childNodes[i];
    • sibling node = div.nextSibling;
  • Relations (HTML elements only)
    • children element = div.children[i];
    • sibling element = div.nextElementSibling;

This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.

like image 196
Ryan Stein Avatar answered Oct 07 '22 20:10

Ryan Stein