tags:

views:

71

answers:

3

Hi, 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>
</div>
</div>

Thanks

+1  A: 

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.

Andy E
Cool thanks. What if I want to do this:objP.innerText = "Sending Data (<a href='javascript:S_Utils_HideModal();'>cancel</a>)";Also I'm wanting to show this Modal box when a user submits a form, what would I add to the HideModal function to stop the page if it's in the middle of a postback? Thanks
Cameron
@Cameron: If you're adding HTML to the `<p>`, you can use the `innerHTML` property instead of `innerText`, or you can create the `<a>` element with `createElement` again and append it after setting the `innerText` property.
Andy E
A: 
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.

William
A: 

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

saturation