Add, Remove, or Replace a CSS Class Using Javascript

Now honestly, I think the all famous Prototype has something for this, but if you aren’t using the all famous Prototype… well you’re screwed. Until now.

This is the idea, you want show or hide something on a click of it.

    <div onclick="HideOrShowMe();">
      YAYAAYAYAY!
    </div>

Annoying thing is trying to keep up with whether it’s hidden or not. Now there are ways to do this for sure, but if you had them you wouldn’t be here… or you just love idiotic banter. Either way, you’re here.

To start, get a class going:

    if (typeof ClassHandler != 'object')
    {
      ClassHandler = new Object();
    }

Normal declaration. Yeehaw. Now we need a method to check for the class:

ClassHandler.CheckForClass = function(element, nameOfClass)
{
    var returnValue = false;

    //Check to see if the element variable is a string or (hopefully) a control.
    //If it is a string, get the control that belongs to that id.
    if (typeof element == 'string')
    {
        element = document.getElementById(element);
    }

    //next you use a regular expression to check the className property for
    //  the class you want.  If it finds a match, you're good to go.
    if (element.className != '')
    {
        returnValue = new RegExp('\\b' + nameOfClass + '\\b').test(element.className);
    }

    return returnValue;
}

Ok so now you have a method to check if it’s there… but what about if you want to replace the old one with a new one? Well that could be broken into two methods first (Both that are useful). First one is the removal of the old class:

ClassHandler.RemoveClass = function(element, nameOfClass)
{
    var returnValue = false;

    //You know the drill
    if (typeof element == 'string')
    {
        element = document.getElementById(element);
    }

    //Hey cool, I just used the CheckForClass method
    if (ClassHandler.CheckForClass(element, nameOfClass))
    {
        //Real simple, replace the old
        //But you have to check if the nameOfClass exists with a preceding space
        //If it does, then you replace that with a space, other wise just replace
        //the nameOfClass with a space.
        element.className = element.className.replace((element.className.indexOf(' ' + nameOfClass) >= 0 ? ' ' + nameOfClass : nameOfClass),'');
        returnValue = true;
    } 

    return returnValue;
}

And now you’ll have to add in the new one.

ClassHandler.AddClass = function(element, nameOfClass)
{
    var returnValue = false;
    //lalalala
    if (typeof element == 'string')
    {
        element = document.getElementById(element);
    }
    //If className already has a value, precede the nameOfClass with a space
    // otherwise just add it in.
    if (!ClassHandler.CheckForClass(element, nameOfClass))
    {
        element.className += (element.className ?  '  '  :  '') + nameOfClass;
        returnValue = true;
    } 

    return returnValue;
}

Now for the replace:

ClassHandler.ReplaceClass = function(element, classToRemove, classToAdd)
{
    var returnValue = false;

    //african elephants only have four teeth for chewing their food.
    if (typeof element == 'string')
    {
        element = document.getElementById(element);
    }

    //Remove the old one
    //Add the new one
    if(ClassHandler.CheckForClass(element, classToRemove))
    {
        ClassHandler.RemoveClass(element, classToRemove);
        ClassHandler.AddClass(element, classToAdd);
        returnValue = true;
    }

    return returnValue;
}

Now you might be thinking, “Tool, why don’t you just use the replace method in the replace method.” Well I suppose you could, but this way you have two other methods at your disposal for future use. Up to you really, part of this was because I actually needed those methods and the title says “Add, Remove, or Replace”. I can’t go against the title. I don’t have that kind of strength.

Usage? Well there are couple ways you can do this.

    if(ClassHandler.CheckForClass('someDiv', 'hide'))
    {
       ClassHandler.ReplaceClass('someDiv', 'hide', 'show');
    }
    else
    {
       ClassHandler.ReplaceClass('someDiv', 'show', 'hide');
    }

or this:

    if(!ClassHandler.ReplaceClass('someDiv', 'hide', 'show'))
    {
       ClassHandler.ReplaceClass('someDiv', 'show', 'hide'));
    }

And other ways to be sure. Now I’m not saying this is the best way to do it, just a decent way… although looking back on this I wonder if I could clean up the regex stuff.

Javascript Anonymous Methods and How they help Ajax WebMethod

Ok so here’s what you’re trying to do:

You have a button and when it’s pressed you want to have it fill a drop down list without a postback. So your first thoughts are, “I like Mentos” followed by, “WebMethod” since you of course read this super awesome post. Now it might look like this:

        function GetUserList()
        {
            PageMethods.GetUserList(OnGetUserListComplete);
        }

        function OnGetUserListComplete(result)
        {
            var dropdownList = $get('dropdownListID');
            for (var i = 0; i < result.length; i++)
            {
                var item;
                item = document.createElement("option");
                item.text = result[i].UserName;
                item.value = result[i].UserID;
                dropdownList.options.add(item);
            }
        }

And GetUserList would be called on click. Fine and dandy, but this sort of bad since you’re hardcoding the id of the control. Meh. You look back at the method and see that there just isn’t a way to pass in a name, and if you didn’t you would be sooooo wrong it hurts. Shame on you. Good thing I’m here. The way you’re going to do this is to use an anonymous method. You see, as it is the PageMethod call needs a method to call post completion and that’s all it takes in. (Well not completely true, it can take in parameters for the server side method, but that’s not the point.) So you have to find a way for that PageMethod to call the method after completion AND make sure it has the list name with it.

        function GetUserList(dropdownList)
        {
            PageMethods.GetUserList(function(result) {
                 OnGetUserListComplete(result, dropdownList); });
        }

        function OnGetUserListComplete(result, dropdownList)
        {
            for (var i = 0; i < result.length; i++)
            {
                var item;
                item = document.createElement("option");
                item.text = result[i].UserName;
                item.value = result[i].UserID;
                dropdownList.options.add(item);
            }
        }

Ooo pretty tricky huh?

        PageMethods.GetUserList(function(result) {
                 OnGetUserListComplete(result, dropdownList); });

See what I did there, I created an anonymous method to be called on completion and in turn it calls the original (Though modified) OnGetUserListComplete method now. And you thought javascript sucked.

Call Server Side methods With Javascript in ASP.Net… Yeah Ajax

So I’ve been looking for something to match the simplicity of the old Ajax.dll WebMethods (The ability to asychronously call a method on a class from javascript) since the project was abandoned by the owner. A lot of what I saw before involved WebServices which wasn’t horrible, but I wanted Ajax.WebMethods. Come to find out, this simplicity exists in 3.5.

So let’s say I want to click on a div and have it’s innerHTML be filled with some string. Sounds like a completely viable situation for any money making business… Anyways, I could do some kind of post back and fill it, or I could use an update panel (Uhg) or I could use a Web Service or I could just bang my head on the desk and get the same level of satisfaction. But then came 3.5 and something wonderful. Take this page:

    public partial class Test : System.Web.UI.Page
    {
        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        public static String GiveMeString()
        {
            return "hi";
        }
    }

See somethig weird? Yeah that’s the magic of the class file. All I need is:

  • A Static Method
  • The WebMethod Attribute
  • The ScriptMethod attribute
  • Optionally something to return, but for this example it’s not optional just like Burt Renold’s mustache

And now the page file is ready, but what about the markup? Well, that’s next, so glad you asked. First the javascript:

        function ShowString()
        {
            var test = $get('ShowThings');
            PageMethods.GiveMeString(OnGiveMeStringComplete);
        }

        function OnGiveMeStringComplete(result)
        {
            var test = $get('ShowThings');
            test.innerHTML = result;
        }

First method is the method to call. The PageMethods object will allow the use of the class method that was created. The parameter being sent in is actually the method needing to be called when the server side call is complete. With that in mind, guess what the second method is… No, not ice cream. It’s the method called when the server call is compete. As you can see, I am simply changing the innerHTML of a div.

    <form id="form1" runat="server">
        <asp:ScriptManager ID="smMain" runat="server" EnablePageMethods="true" />
        <div id="ShowThings" style="background-color:Yellow;height:20px;width:20px;"
          onclick="ShowString()"></div>
    </form>

And there you have the markup. ScriptManager is a must in this case, but that’s pretty standard when dealing with Ajax in asp.net. The only other thing of note is the method call on the div’s onClick. Beyond that, it’s ready to go. And if you were to make this example yourself and click on the div, you will get a ‘hi’ string in it on the first click. Amazing.

Use Javascript and an HttpHandler to Load an Image from a Database

This might be part of another ongoing series, but the for this post, right here, RIGHT NOW, I am going to show are really simple but fun (??) way to change an image’s… eh image from a database stored image using Javascript and an .ashx file. And when I say simple, I mean it took me longer to get test code going than it did to make this work.

First you need a handler (If you don’t what this is for, well for this example it allows you to create a non existant url for an image loaded from the database.) which is aptly named Generic Handler when you do the usual Add New Item. Amazing. You should get something like this in the class file:

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class SomeImage: IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello World");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

Yeah you like that don’t you? Yeah you do.

So now we have something to display the image right? Well that’s pretty easy too. For me, I have an UserImage class I created with Linq to Sql to mimic my UserImage table. I’m cool like that. I then created a method to return the image bytes based on the ID sent in. That part is up to you how to handle. The main thing you need is to get the image bytes somehow. With that in mind, here is what the class file looks like now:

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ShowImage : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            Int32 imageID;
            Byte[] imageBytes;

            imageID = Convert.ToInt32(context.Request.QueryString["ImageID"]);
            imageBytes = UserImage.GetImageBytesById(imageID);
            context.Response.ContentType = "image/jpeg";
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.BufferOutput = false;
            context.Response.OutputStream.Write(imageBytes, 0, imageBytes.Length);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

As you can see, the query string has an id being sent in and I’m retrieving it. From there I get the image bytes, tell the context what it is, how to handle the cache, and sending the bytes out. What you can’t see right now is that somewhere I have something that looks like this:

   <image src="SomeImage.ashx?ImageID=1" />

When that url is read, it will send it off to the handler to get and display the image. (Not taking caching into account mnd you)

Now I know what you’re thinking right now, “I’m bored” which I understand but you’re also thinking, “Where’s the f@&#ing javascript?”. Well my vulgar friend, it’s on the way.

<head runat="server" >
        <script type="text/javascript" language="javascript">
        function TestThis(name, imageID)
        {
            var test = document.getElementById(name);
            test.src = 'ShowImage.ashx?imageID=' + imageID;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div style="background-color:Gray;height:20px;width:20px;" onclick="TestThis('hi', 1);"> </div>
        <div style="background-color:Red;height:20px;width:20px;" onclick="TestThis('hi', 2);" > </div>
        <div style="background-color:Blue;height:20px;width:20px;" onclick="TestThis('hi', 3);"> </div>
        <br />
        <img src="" id="hi" name="hi" />
    </div>
    </form>
</body>

So now every time one of the three divs is “clicked”, the image is changed depending on the image id sent in using the “url” of the handler you created. Much like sending information to another page, you send the id to the handler so it can display the correct image.

I realize this isn’t the best of examples but it’s a push in the right direction. Maybe next time you want something, you won’t swear at me.

Ajax Control Library: Autocomplete Control to Scriptcontrol

[Part One] [Part Two] [Part Three] [Part Four] [Part Five]

Ok so in part four I showed you how to create a webcontrol from the AutoComplete control, so now it’s time to take the first four lessons and combine them. Now it’s time to have an autocomplete script control. The first part is really simple, just like before you have to:

  • Inherit from ScriptControl
  • Override the GetScriptDescriptors and GetScriptReferences methods
  • Create the .js file
  • Make the .js file an embedded resource
  • Update the assemblyinfo file in the Properties folder
  • Add the minimal needed javascript

So it will look something like this:

public class AutocompleteScriptControl : ScriptControl, INamingContainer
{
  private AutoCompleteExtender autoComplete;
  private TextBox textboxTarget;

  protected override void CreateChildControls()
  {
    base.CreateChildControls();

    autoComplete = new AutoCompleteExtender();
    autoComplete.ID = "autoCompleteMain";

    textboxTarget = new TextBox();
    textboxTarget.ID = "textboxTarget";

    Controls.Add(textboxTarget);
    Controls.Add(autoComplete);
  }

  protected override void OnPreRender(EventArgs e)
  {
    base.OnPreRender(e);
    autoComplete.TargetControlID = textboxTarget.ID;
  }

  protected override IEnumerable<ScriptDescriptor> GetScriptDescriptors()
  {
    ScriptControlDescriptor desc =
      new ScriptControlDescriptor("Test.Examples.Client.AutocompleteScriptControl", ClientID);
    desc.AddProperty("textboxTargetID", textboxTarget.ClientID);
    desc.AddProperty("autocompleteID", autoComplete.ClientID);

    return new ScriptDescriptor[] { desc };
  }

  protected override IEnumerable<ScriptDescriptor> GetScriptReferences()
  {
    return new [] { new ScriptReference
      ("Test.Examples.AutoCompleteExample.AutocompleteScriptControl.js", "Test.Examples") };
  }

}

And the script file:

if (Type)
{
    Type.registerNamespace("Test.Examples.Client");
}

Test.Examples.Client.AutocompleteScriptControl = function(element)
{
    Test.Examples.Client.AutocompleteScriptControl.initializeBase(this, [element]);

    this._autocompleteID = "";
    this._textboxTargetID = "";

    this._autoComplete = null;
    this._textboxTarget = null;
}

Test.Examples.Client.AutocompleteScriptControl.prototype =
{
    get_autocompleteID: function()
    {
        return this._autocompleteID;
    },

    set_autocompleteID: function(value)
    {
        this._autocompleteID = value;
    },

    get_textboxTargetID: function()
    {
        return this._textboxTargetID;
    },

    set_textboxTargetID: function(value)
    {
        this._textboxTargetID = value;
    },

    initialize: function()
    {
        this._autoComplete = $get(this._autocompleteID);
        this._textboxTarget = $get(this._textboxTargetID);

        Test.Examples.Client.AutocompleteScriptControl.callBaseMethod(this, 'initialize');
    },

    dispose: function()
    {
        Test.Examples.Client.AutocompleteScriptControl.callBaseMethod(this, 'dispose');
    }
}

/***********************************/

Test.Examples.Client.AutocompleteScriptControl.registerClass
    ('Test.Examples.Client.AutocompleteScriptControl', Sys.UI.Control);

And now this is the bare minimum needed to get this done.

Return False from a ScriptControl method and why I hate Firefox…

I have to admit that it might be IE that is wrong, but I don’t know. That and I do kind of hate Firefox so I’ll stand by the title anyhow.

This is a little off the current beaten path, but does deal with the current ScriptControl theme so I thought I’d put it in here.

Here’s the problem: You have a script control, a button, and want to have the person confirm before it’s allowed to postback. Easy right? If this were the non script control way you would do this:

Javascript:

    function ReturnFalse()
    {
      var confirmed = confirm('Is there anyone more awesomer that Sean?');
      return confirmed;
    }

Markup:

  <asp:Button ID="whoCares" runat="server" OnClientClick="return ReturnFalse();" >

Class Stuff:

  whoCares.Click += whoCares_Click;
  ...
  private void whoCares_Click(object sender, EventArgs e)
  {
    throw new NotImplementedException();
  }

Basically what I’ve done is made it so that if it doesn’t return false, an exception is thrown. Easy test. Works in both browsers right? Brilliant.

Now for the script control:

  handleLnkDeleteButtonClick: function(e)
  {
      var confirmed = confirm('Is there anyone more awesomer that Sean?');
      return confirmed;
  },

 initialize: function()
 {
    this._lnkDeleteButton = $get(this._lnkDeleteButtonID);
    this._lnkDeleteButton.idpicker = this;

    //HOOK BEGINS HERE
    this._lnkDeleteButtonClick = Function.createDelegate(this, this.handleLnkDeleteButtonClick);
    $addHandler(this._lnkDeleteButton, "click", this._lnkDeleteButtonClick);
    //END HOOK HERE

    NDI.WebControls.Client.PersonalMessageTypePicker.callBaseMethod(this, 'initialize');
},

Now that looks ok right? The method pops up the confirmation button alert dialogue thingy and returns the answer but guess what, you’re wrong. So wrong. In IE this works but in Firefox, sorry no deal. Firefox will ignore anything returned if the “return” keyword is not in the markup. Well from here there’s no real markup so how the hell would I do that? Well yes Virginia there is a Santa Clause and he lives in e.preventDefault();

It’s actually really simple, one small change in the handling method. You replace return X with e.preventDefault();

  handleLnkDeleteButtonClick: function(e)
  {
    var confirmed = confirm('This will delete the currery Message category
      and move all messages to the Oprhan cataegory.  Allow?');
    if (!confirmed)
    {
        e.preventDefault();
    }
  },

And now it works. Yes you can thank me with large donations of money or cheese.

Handle Events and Add Controls to Script Controls (ASP.Net ScriptControl)

[Part One] [Part Two] [Part Three] [Part Four] [Part Five]

Ok in the last post I went over the creation of a web control. Simple enough as you can see. Now it’s time to screw around with Controls and how to capture their events client side. Something only a brilliant person like me could figure out… I so wish that were true. I could make millions.

Let’s add a control to the eh… control. Say we want to throw an alert everytime a person focuses on a textbox. Yes, that’s really stupid but it’s easy so live with it. Let’s use the class from the other post:

  public class ScriptControlExample : ScriptControl , INamingContainer
  {
     private TextBox textboxStupid;

     protected override void CreateChildControls()
     {
       base.CreateChildControls();

       textboxStupid = new TextBox();
       textboxStupid.ID = "textboxStupid";
       Controls.Add(textboxStupid);
     }

      protected override IEnumerable<ScriptDescriptor> GetScriptDescriptors()
      {
        ScriptControlDescriptor desc = new ScriptControlDescriptor
          ("Test.Examples.Client.ScriptControlExample", ClientID);
        desc.AddProperty("textboxStupid", textboxStupid.ClientID);

        return new ScriptDescriptor[] { desc };
      }

      protected override IEnumerable<ScriptReference> GetScriptReferences()
      {
         return new ScriptReference[] { new ScriptReference
           ("Test.Examples.ScriptControlTemplate.ScriptControlExample.js", "Test.Examples") };
      }
    }

Notice anything new? I added a textbox, created it in the CreateChildControls method, then added soemthing new to the GetScriptDescriptors method. Remeber the GetScriptDescriptors method is used to send values to the client from the server. Here I am sending the clientID of the textbox… can you guess why? That’s right, because I’m going to use it to find the control client side. Now for the JavaScript end.

  if (Type)
  {
    Type.registerNamespace("Test.Examples.Client");
  }

  NDI.WebControls.Client.GenericAutoComplete = function(element)
  {
      NDI.WebControls.Client.GenericAutoComplete.initializeBase(this, [element]);

      //Textbox ID value
      this._textboxStupidID = "";
      //Textbox Control
      this._textboxStupid = null;
      //Event Handler
      this._textboxStupidOnFocus = null;
  }

  Test.Examples.Client.ScriptControlExample.prototype =
  {
    //Properties for the _textboxStupidID field
    get_textboxStupidID : function()
    {
        return this._textboxStupidID;
    },

    set_textboxStupidID : function(value)
    {
        this._textboxStupidID = value;
    },

    //Method to be called on focus
    handleOnTextBoxFocus : function(e)
    {
        alert('hi');
    },    

     initialize: function()
    {
        //Find and set the textbox field using the passed in ID
        this._textboxStupid = $get(this._textboxStupidID);

        //Create a delegate to handle the onFocus event
        //Basically creating a means to call the handleOnTextBoxFocus method
        this._textboxStupidOnFocus = Function.createDelegate(this, this.handleOnTextBoxFocus);

        //Set the onFocus event to be handled
        $addHandler(this._textboxStupid, "focus", this._textboxStupidOnFocus);

        Test.Examples.Client.ScriptControlExample.callBaseMethod(this, 'initialize');
    },

    dispose: function()
    {
        //Remove the event handling when this is all said and done.  A clean up.
        $removeHandler(this._textboxStupid, "focus", this._textboxStupidOnFocus);
        Test.Examples.Client.ScriptControlExample.callBaseMethod(this, 'dispose');
    }
  }
  //Same as before
  Test.Examples.Client.ScriptControlExample.registerClass(
    'Test.Examples.Client.ScriptControlExample', Sys.UI.Control);

Oooooooooook So some added things, yes? Well I’ll go through them:

  NDI.WebControls.Client.GenericAutoComplete = function(element)
  {
      NDI.WebControls.Client.GenericAutoComplete.initializeBase(this, [element]);

      //Textbox ID value
      this._textboxStupidID = "";
      //Textbox Control
      this._textboxStupid = null;
      //Event Handler
      this._textboxStupidOnFocus = null;
  }

This is basically declaring the fields for the class and setting their defaults. For this example we’ll need the field to hold the ID in, a field to represent the textbox oject, and a field to represent the delegate later on used to hook up the onFocus Event.

Note: In the next bit you will notice that every method/property is followed by a comma. Do not forget that.

Next, let’s look at the actual class definition. First we’ll start at the properties:

  Test.Examples.Client.ScriptControlExample.prototype =
  {
    //Properties for the _textboxStupidID field
    get_textboxStupidID : function()
    {
        return this._textboxStupidID;
    },  //SEE COMMA

    set_textboxStupidID : function(value)
    {
        this._textboxStupidID = value;
    },  //ANOTHER COMMA

    .....

First thing you’ll notice is the :fuction notation. This is used to declare both methods and properties. Nothing huge, just something to note.

Second thing you might notice is that the property names look a little hard coded and you would be right. Remember how the value send out from the class file was named “textboxStupidID”? Well guess what, for .net to be able to attach that value to a client property, you have to name the properties exactly the same with with either get_ or set_ preceding. Not perfect, but since I’m the only perfect thing in existence, I guess it will have to do.

Now onto the method we need:

    ....

    //Method to be called on focus
    handleOnTextBoxFocus : function(e)
    {
        alert('hi');
    },  

    ....

Wow… uh well it’s a method and it takes in an argument. What the hell do you want from me?

Onto the intialization/Constructorish thing:

     initialize: function()
    {
        //Find and set the textbox field using the passed in ID
        this._textboxStupid = $get(this._textboxStupidID);

        //Create a delegate to handle the onFocus event
        //Basically creating a means to call the handleOnTextBoxFocus method
        this._textboxStupidOnFocus = Function.createDelegate(this, this.handleOnTextBoxFocus);

        //Set the onFocus event to be handled
        $addHandler(this._textboxStupid, "focus", this._textboxStupidOnFocus);

        Test.Examples.Client.ScriptControlExample.callBaseMethod(this, 'initialize');
    },

This might be the least easy part of the whole thing. The first commentented area:

    this._textboxStupid = $get(this._textboxStupidID);

Simple just gets the textbox by the passed in ID. I swear this will get more complicated.

    this._textboxStupidOnFocus = Function.createDelegate(this, this.handleOnTextBoxFocus);

This gives a variable that points to the method we want to use when the focus event fires. Still waiting for complicated…

   $addHandler(this._textboxStupid, "focus", this._textboxStupidOnFocus);

This assigns the method we want, through the delegate, to the focus event on the textbox. Hrm. Ok so not really complicated. Just messy looking. One this to note though is that the events on all the controls won’t have the “on” prefix. So if you can’t figure out why you’re getting an error because it can’t find the event, try dropping the “on”.

And there you have it. Now you are free to run it and be really annoyed by how dumb this example was. Next will be using this for the power of evil by adding an autocomplete control with a processing image.

You can do that in Javascript: Dynamically Create Divs

Creating divs on the fly and assigning methods:

As I have been working with Script Controls lately, I’ve been forces to learn more about javascript…. yeah I know, bleh. However, in my learnin’ I’ve actually been forced to like Javascript…. yeah I know, bleh.

Well one this I was doing was tranfering a front end control to a Script Control. Basically I am building an Auto Complete control that is using the Ajax.dll AjaxMethod stuff. Thus skipping the need for web services that the Ajax Control AutoComplete needs. Anyhow, the reason I am saying this is that it gets a list of Users and dynamically creates a list of divs that change color when hovered over and fill in a textbox when selected. Originally I was doing this by creating the html needed, then appending the innerHTML property on the container div.

function buildSelectableDiv(currentCount, innerText, textboxName, parentDiv)
{
   var defaultClass;
   var divChild;
   var divToAdd;
   var picker;

   //create the parent div
   divToAdd = document.createElement('div');
   //set the id of the div
   divToAdd.setAttribute('name', 'divNames' + currentCount);

   //Create child div
   divChild = document.createElement('div');
   //getting the child ready
   divChild.setAttribute('name', 'divNamesChild' + currentCount);

   //Add child to new parent
   divToAdd.appendChild(divChild);

   return divToAdd;
}

And there you go. Creating a div and adding div to it.