<div>를 생성하고 <div>를 동적으로 추가


128

내부 <div>가 추가 <div>되어 동적으로 만들려고합니다 . 나는 지금까지 작동하는 이것을 가지고있다 :

var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);

두 번째 div를 만들고 첫 번째 div에 추가하는 데 문제가 있습니다.

본질적으로 이것을 최종 마크 업으로 사용하고 싶습니다.

<div id="block" class="block">
   <div class="block-2"></div>
</div>

19
그것은 body 요소를 얻는 이상한 방법입니다 ... 그냥 사용하십시오 document.body.
Guffa December

답변:


234

동일한 프로세스를 사용하십시오. 이미 만든 iDiv원래 요소 <div id='block'>를 참조 하는 변수 가 이미 있습니다 . 다른 것을 만들고 <div>호출하면 appendChild()됩니다.

// Your existing code unmodified...
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);

// Now create and append to iDiv
var innerDiv = document.createElement('div');
innerDiv.className = 'block-2';

// The variable iDiv is still good... Just append to it.
iDiv.appendChild(innerDiv);

http://jsfiddle.net/W4Sup/1/

이벤트 생성 순서는 내가 위에서했던 것처럼 될 필요는 없습니다. innerDiv에 둘을 추가하기 전에 새 div를 외부 div에 번갈아 추가 할 수 있습니다 <body>.

var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';

// Create the inner div before appending to the body
var innerDiv = document.createElement('div');
innerDiv.className = 'block-2';

// The variable iDiv is still good... Just append to it.
iDiv.appendChild(innerDiv);

// Then append the whole thing onto the body
document.getElementsByTagName('body')[0].appendChild(iDiv);

3
'추가 마일'을가는 것은 이야기의 도덕이었다 :-)!

또한 다음을 사용하여 마지막 줄을 줄일 수 있습니다. document.body.appendChild (iDiv);
idan hav

8
var iDiv = document.createElement('div');

iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);

var div2 = document.createElement('div');

div2.className = 'block-2';
iDiv.appendChild(div2);

Michael Berkowski
Oliver Bayes-Shelton의

3
나는 그렇게 할 수 있다고 생각하지 않습니다. 간단한 솔루션은 일반적으로 분산이 적습니다.
Moazzam Khan

4
var iDiv = document.createElement('div'),
    jDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
jDiv.className = 'block-2';
iDiv.appendChild(jDiv);
document.getElementsByTagName('body')[0].appendChild(iDiv);

3

글쎄, 이것이 얼마나 동적인지는 모르겠지만 때로는 디버깅 수명을 절약 할 수 있습니다.

var daString="<div id=\'block\' class=\'block\'><div class=\'block-2\'></div></div>";
var daParent=document.getElementById("the ID of whatever your parent is goes in here");
daParent.innerHTML=daString;

"Rat javascript"내가 제대로했다면. div와 내용이 동적이지 않을 때 직접 작동하거나 문자열을 조작하여 변경 할 수도 있습니다. 문자열 조작이 "element.property = bla"접근법보다 복잡하지만 매우 환영합니다. 유연성, 그리고 훌륭한 디버깅 도구이기도합니다. :) 도움이되기를 바랍니다.


2
var i=0,length=2;

     for(i; i<=length;i++)
 {
  $('#footer-div'+[i]).append($('<div class="ui-footer ui-bar-b ui-footer-fixed slideup" data-theme="b" data-position="fixed" data-role="footer" role="contentinfo" ><h3 class="ui-title" role="heading" aria-level="1">Advertisement </h3></div>')); 

 }

JavaScript 라이브러리를 사용 중이고 예제에서 원래 질문과 다른 마크 업을 사용하고 있음을 나타내는 것이 좋을 것입니다.
rob

2
window.onload = function() {
  var iDiv = document.createElement('div');
  iDiv.id = 'block';
  iDiv.className = 'block';
  document.body.appendChild(iDiv);

  var iiDiv = document.createElement('div');
  iiDiv.className = 'block-2';

  var s = document.getElementById('block');
  s.appendChild(iiDiv);
}

1
var arrayDiv = new Array();
    for(var i=0; i <= 1; i++){
        arrayDiv[i] = document.createElement('div');
        arrayDiv[i].id = 'block' + i;
        arrayDiv[i].className = 'block' + i;
    }
    document.body.appendChild(arrayDiv[0].appendChild(arrayDiv[1]));

0
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';

var iDiv2 = document.createElement('div');
iDiv2.className = "block-2";

iDiv.appendChild(iDiv2);
// Append to the document last so that the first append is more efficient.
document.body.appendChild(iDiv);

0
    while(i<10){
               $('#Postsoutput').prepend('<div id="first'+i+'">'+i+'</div>');
               /* get the dynamic Div*/
               $('#first'+i).hide(1000);
               $('#first'+i).show(1000);
                i++;
                }
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.