views:

593

answers:

1

I am creating a dynamic select box, on change a text section will get populated with data. I would rather have the data set to some text as opposed to being append.

For example:

This function gets called when a select box is changed:

function createDetails(...) {

    var details = document.getElementById("detailsDIV");
    var docFragment = document.createDocumentFragment();
    containerDiv = document.createElement("div");

    // Create five div sections with the text for the details section
    var nameTextNode    = createTextDivSect(nameStr);
    var phoneTextNode   = createTextDivSect("Phone:  " + phoneStr);
    var faxTextNode     = createTextDivSect("Fax:    " + faxStr);
    var websiteTextNode = createTextDivSect("Website: " + websiteStr);
    var emailTextNode   = createTextDivSect("Email: " + emailStr);

    // Append the text sections to the container DIV
    containerDiv.appendChild(nameTextNode);
    containerDiv.appendChild(phoneTextNode);
    containerDiv.appendChild(faxTextNode);

    // Add the container div to the doc fragment
    docFragment.appendChild(containerDiv);
    // Add the doc fragment to the div
    details.appendChild(docFragment);
}

////

With this approach, it is assuming I am appending to a section. Is there a way I can just SET the child. I guess I could remove the child and then set it. But I figure that would waste resources.

+1  A: 

If you want to set an entire div at once without using innerHTML, you can use replaceChild():

function createDetails(...) {

    var details = document.getElementById("detailsDIV");
    var docFragment = document.createDocumentFragment();

    // Process docFragment here...

    var parentNode = details.parentNode;
    parentNode.replaceChild(docFragment, details);
}
Daniel Lew
I was trying to avoid innerHtml.I wish there were a:var details = document.getElementById("detailsDIV");details = newDocFragment.Can I do that?
Berlin Brown
Sort of. I've updated my answer with what I think is closer to what you want.
Daniel Lew