Utwórz <div> i dołącz <div> dynamicznie


128

Staram się stworzyć <div>dynamicznie, z dopiskiem <div>wewnątrz. Do tej pory mam to, które działa:

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

Mam problem z utworzeniem i dołączeniem drugiego elementu DIV do pierwszego elementu DIV.

Zasadniczo chcę to zrobić jako ostateczny znacznik:

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

19
To dziwny sposób na uzyskanie elementu ciała ... po prostu użyj document.body.
Guffa,

Odpowiedzi:


234

Użyj tego samego procesu. Masz już zmienną, iDivktóra nadal odnosi się do oryginalnego elementu <div id='block'>, który utworzyłeś. Musisz tylko utworzyć inny <div>i zadzwonić 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/

Kolejność tworzenia wydarzeń nie musi być taka, jaką mam powyżej. Możesz naprzemiennie dołączyć nowy element innerDivdo zewnętrznego elementu DIV, zanim dodasz oba elementy do elementu <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
Dążenie do „dodatkowej mili” było morałem tej historii :-)!

można również skrócić ostatnią linię za pomocą: 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);

prawie skopiowałeś Michaela Berkowskiego
Olivera Bayesa-Sheltona

3
Nie sądzę, żebym mógł to zrobić. Proste rozwiązania mają zwykle małą wariancję: D.
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

Cóż, nie wiem, jak dynamiczne jest to, ale czasami może to uratować życie przy debugowaniu:

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" Jeśli zrobiłem to poprawnie. Działa bezpośrednio, gdy element div i zawartość nie są oczywiście dynamiczne, lub możesz nawet manipulować łańcuchem znaków, aby to zmienić, chociaż operowanie ciągiem znaków jest bardziej złożone niż podejście "element.property = bla", to daje bardzo mile widziane elastyczność i świetne narzędzie do debugowania :) Mam nadzieję, że to pomoże.


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>')); 

 }

mogłoby być miło wskazać, że korzystasz z biblioteki JavaScript i że Twój przykład używa innych znaczników niż oryginalne pytanie.
obrabować

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++;
                }
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.