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

后端 未结 2 1570
予麋鹿
予麋鹿 2020-12-02 03:46

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 w

相关标签:
2条回答
  • 2020-12-02 03:51
    • 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.

    0 讨论(0)
  • 2020-12-02 04:07

    Have you tried JQuery? Vanilla javascript can be tough. Try using this:

    $('.container-element').add('<div>Insert Div Content</div>');
    

    .container-element is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add() function inserts HTML into the container-element.

    0 讨论(0)
提交回复
热议问题