开发者

How to append div tag dynamically in html using javascript/

I am creating one div dynamically and want to add it inside another div.

           (js) var divtag = document.createElement("div");
                divtag.innerHTML = xmlhttp.responseText;//Ajax call working fine
               开发者_如何学编程 document.getElementById('con').appendChild(divtag);

html:

enter code here <div id="con"></div>

The the o/p I am getting from AJAX call is Ok, also i am able to view it in browser, but when I am doing a view source I am unable to see the div and its contents. It should come as :

enter code here <div id="con">
              <div>
           Contents added @ runtime
         </div>
          </div>

Can somebody suggest where I am going wrong?


You won't see the generated code in the browser by default, but you can use the Firefox extension Web Developer to view the code generated after executing js.

-- edit

also helpful extension for FF - FireBug.


Use firebug - the best firefox web development addon in my opinion.

With firebug you can inspect the DOM:

How to append div tag dynamically in html using javascript/


(source: mozilla.org)


Do you have "con" div loaded on our DOM?

var divtag = document.createElement("div");
divtag.innerHTML = xmlhttp.responseText;//Ajax call working fine
// See before adding a child, does it exist?
alert(document.getElementById('con'));
document.getElementById('con').appendChild(divtag);

I don't know where you having this code. As it is important that the DOM should be loaded before checking/assigning anything to an element. To avoid such a mistake:

function addEvent(obj, evType, fn){ 
 if (obj.addEventListener){ 
   obj.addEventListener(evType, fn, false); 
   return true; 
 } else if (obj.attachEvent){ 
   var r = obj.attachEvent("on"+evType, fn); 
   return r; 
 } else { 
   return false; 
 } 
}
addEvent(window, 'load', function() {
      var divtag = document.createElement("div");
      divtag.innerHTML = xmlhttp.responseText;//Ajax call working fine
      // See before adding a child, does it exist?
      alert(document.getElementById('con'));
      document.getElementById('con').appendChild(divtag);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜