开发者

JavaScript createElement help

I have the following code:

function JS_Utils_BuildModal ()
        {

            var objModal = document.createElement("div");

            objModal.setAttribute('id', 'Modal');

            document.body.appendChild(objModal);

        }

What I want to do is add to it and create a series of DIVS and P's with some content so that when I run the function I get the following:

<div id="Modal">
<div class="Content">
<p>Sending Data</p&g开发者_运维百科t;
</div>
</div>

Thanks


Really it's just a matter of duplicating the createElement and appendChild parts of your code, and then setting the relevant properties on the other objects:

function JS_Utils_BuildModal () 
{ 
    var objModal   = document.createElement("div"); 
    var objContent = document.createElement("div");
    var objP       = document.createElement("p");
    objModal.setAttribute('id', 'Modal');
    objContent.className = 'Content';
    objP.innerText = "Sending Data";
    objModal.appendChild(objContent);
    objContent.appendChild(objP); 
    document.body.appendChild(objModal); 
} 

Alternatively, you could do the whole thing/part of it with the innerHTML property, like so:

function JS_Utils_BuildModal () 
{ 
    var objModal   = document.createElement("div");
    objModal.setAttribute('id', 'Modal');
    objModal.innerHTML = '<div class="Content"><p>Sending Data</p></div>';
    document.body.appendChild(objModal); 
}

Using innerHTML is generally slower than directly manipulating the DOM, because it invokes the HTML parser. It's still fast enough in most cases, though.


function JS_Utils_BuildModal()
{
    // Create parent div
    var objModal = document.createElement("div");
    objModal.setAttribute('id', 'Modal');
    document.body.appendChild(objModal);

    // Create modal div
    var objContent = document.createElement("div");
    objContent.setAttribute("id", "Content");
    objModal.appendChild(objContent);

    // Create sending data paragraph
    var objData = document.createElement("p");
    objContent.appendChild(objData);
}

The appendChild() method will work on any DOM element. document.body is a DOM element for the document's body.

Edit: Looks like Andy E already answered the question correctly.


about innerhtml, it is actually faster than dom: http://www.quirksmode.org/dom/innerhtml.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜