Insert Whatever, Wherever You Want

Leave a comment

ChocolateChip simplifies inserting content into a document

DOM level 3 has some new ways of injecting content into a document. And on top of that ChocolateChip has its own handy utility methods for inserting content. Here’s the goods:

  1. Element.insertAdjacentText()
  2. Element.insertAdjacentHTML()
  3. Element.insertAdjacentNode()
  4. $.make()
  5. Element.insert()
  6. Element.before()
  7. Element.after()
  8. Element.fill()
  9. Element.prepend()
  10. Element.append()

All three of the insertAdjacent methods take two parameters, the place to insert and the content to insert. Passing in the correct parameter for position is very important for getting your content where you want it. This means that these insert methods do not replace the contents of the element with the content you pass in. Instead they insert it in juxtaposition to the element. You have four options for where you want to insert. IMPORTANT! These arguments must be in quotes or you’ll get an exception.

This inserts the content immediately before the element so that the content become the previous sibling of the element.
This inserts the content into the element as its first child. This does not replace any other content already in the element.
This inserts the content into the element as its last child. This does not replace any other content already in the element.
This inserts the content immediately after the element so that the content become the next sibling of the element.


This method insert a string of text at the location passed in.

<p id="description">This is the main section.</p>
$(function() {
	$("#description").insertAdjacentText("beforeBegin", "This is before the description: ");
	$("#description").insertAdjacentText("afterBegin", "This is at the beginning of the description: ");
	$("#description").insertAdjacentText("beforeEnd", "This is at the end of the description: ");
	$("#description").insertAdjacentText("afterEnd", "This is after the end of the description: ");


This is similar to the Element.insertAdjacentText() method, except that it creates HTML which it then inserts at the specified locations.

$(function() {
	$("#description").insertAdjacentHTML("beforeBegin", "<p>This is before the description: </p>");
	$("#description").insertAdjacentHTML("afterBegin", "<p>This is at the beginning of the description: </p>");
	$("#description").insertAdjacentHTML("beforeEnd", "<p>This is at the end of the description: </p>");
	$("#description").insertAdjacentHTML("afterEnd", "<p>This is after the end of the description: </p>");	


Like the previous two methods, this method inserts content into the designated locations, except that it uses existing nodes. You could pluck nodes from elsewhere in a document, or create them on the fly for inserting.

$(function() {
	var a1 = $.make("<p>First Paragraph</p>");
	var a2 = $.make("<p>Second Paragraph</p>");
	var a3 = $.make("<p>Third Paragraph</p>");
	var a4 = $.make("<p>Fourth Paragraph</p>");
	$("#description").insertAdjacentElement("beforeBegin", a1);
	$("#description").insertAdjacentElement("afterBegin", a2);
	$("#description").insertAdjacentElement("beforeEnd", a3);
	$("#description").insertAdjacentElement("afterEnd", a4);	


$.make() is a method for creating HTML element nodes on the fly. It takes as its argument a string of valid markup. This must be correct syntax for the doctype used by the target document or the browser will not render it properly.

$(function() {
    var content = $.make("<p>This is a paragraph with some <strong>important</strong> and <em>trivial</em> information.</p>");
     var menu = $.make("<ul id="menu"><li>Item One</li><li>Item Two</li><li>Item Three</li></ul>");


The method does what the label say. It allows you to insert content into another element. The first argument is the content to insert. The second, optional argument is the position at which to insert the content. If no position is supplied it default to inserting the content at the end. As a convenience you can pass in “first” or “last” for a position. Otherwise a digit starting from 1 to indicate the position at which to insert. 1 is equivalent to “first.” If the numerical position passed as an argument is larger than the number of child nodes in the target element, it will be inserted in the last position. If the content passed in is a string, the method attempts to convert it into HTML nodes before inserting. If the content consists of HTML nodes, the method inserts them at the indicated position.

$(function() {
    // Insert this at the beginning:
    $("#response").insert("<p>A new paragraph.</p>", "first");
    // Insert this at the end:
    $("#response").insert("<p>Another paragraph at the end.</p>", "last");
    // Insert this at position 5, that is, as the fifth child of the element:
    $("#response").insert("<p>An important update.</p>", 5);


This method inserts content before the target element. The inserted content thus becomes the target’s previous sibling. The content passed in can be a node or an array of nodes.

$(function() {
     var newNode $.make("<h1>An Important Announcement</h1>");
    $("body > p").before(newNode);


This method inserts content after the target element. Thus the content becomes the next sibling of the target. The content passed in can be a node or an array of nodes.

$(function() {
     var newNode $.make("<li>The last item is always the most important!</li>");


This method replaces the contents of the element with the content passed as an argument. Unlike other methods above, this method does not attempt to convert a string into HTML before insertion. Rather it is primarily for replace the text content of an element with the text passed in. However, if a node is passed it, it will insert it into the element. This method always replaces whatever the content of the element is, even if that consists of multiple child nodes.

$(function() {
    $("#update").fill("This page has just been updated");


As of version 1.1.9 ChocolateChip offers the element.prepend method. This allows you to insert content at the beginning of a collection of nodes. If the parent is empty, the content will simply be inserted. This is just a convenience method to mimic the jQuery equivalent.

$(".menu").prepend("<li>item 1</li><li>item 2</li><li>item3</li>");


As of version 1.1.9 ChocolateChip offers the element.append method. This allows you to insert content at the end of a collection of nodes. If the parent is empty, the content will simply be inserted. This is just a convenience method to mimic the jQuery equivalent.

$(".menu").append("<li>Final item here</li>");

Adding Some Class to Your Document

Comments Off on Adding Some Class to Your Document

ChocolateChip provides several methods working with classes

  1. Element.hasClass()
  2. Element.addClass()
  3. Element.removeClass()
  4. Element.toggleClass()


Sometimes you just need to check an element to see if it has a class or not. To accomplish this use the Element.hasClass() method like this:

$.ready(function() {
    // We want the third paragraph in the document:
	var p = $("p:nth-of-type(3);
	if (p.hasClass("important")) {
		p.fill("This is very important!");
	// Get all list items and check to see if they have the class "medium":
	$$("li").forEach(function(item) {
		if (item.hasClass("medium") {
			item.css("font-size: 14px");
		} else {
			item.css("font-size: 20px");


This method does what the label says, it adds a class to the element:

// Here we're getting the all the list items of the second ul in the docuemnt:
$$("ul:nth-of-type(2) > li").forEach(function(item) {


Use the Element.remove() method to, well, remove a class:

$.ready(function() {
	$$("a").forEach(function(link) {
		if (link.hasClass("external")) {


And now, the best of all, the class toggler method. This method works differently depending on whether you pass in one or two classes to toggle. If a single class is passed, toggleClass() will add the class if the element doesn’t have it, or remove it if the element already has it. However, If you pass in two classes, toggleClass() will check the element to see if it has the first class. If it does, it will remove that class and added the second class. If the element doesn’t have the first class, toggleClass() will added it. Then the next time toggleClass is called, it will toggle the two classes on the element.

$.ready(function() {
	$$("li").forEach(function(item) {
		item.bind("touchestart", function() {
		item.bind("touchend", function() {
	$$("a").forEach(function(link) {
		link.bind("touchstart", function() {
			link.toggleClass("touched", "untouched");

Getting and Setting an Element’s Style

Comments Off on Getting and Setting an Element’s Style

ChocolateChip version 1.1.7

CSS() update

As of version 1.1.7 element.css() has been updated to accept arguments more like jQuery. You no longer need to enclose a string of CSS declarations in curly braces. You can just quote the string. This means that if you have code written with curly braces on for element.css() you’ll need to update that code to work with this version. You can also pass element.css() and object of property/value pairs. When passing an object, if the property is a single word, it does not need to be quoted. If it is a hyphenated property it does need to be quotes. The property values always need to be quoted. Observe the examples below:

// Example of string:
$(".content").css("height: 100%; width: 100%, background-color: #ccc; color: #666; border: solid 2px #666;");

// Simple property and value (can only use once, for more use object notation)
$(".menu").css("border", "solid 1px red");

// Passing in an object of properties and values:
$(".footer").css({height:"100px", width:"100%", color:"#000","background-color":"#fff});

// To get a particular style attribute of an element:
var menuFontColor = $(".menu > li").css("color");

Update Dec 23, 2010

As of version 1.0.8, ChocolateChip no longer has a separate $.style() method. Its functionality has been incorporated into the Element.css() method. The new functionality is explained as follows:

To get the style of an element, simply pass the css() method the property whose value you want:

console.log("The font size is: " + $("#item").css("font-size"));

Note: When ChocolateChip returns a CSS value, this is always a string. This is so even when it appears to be a numerical value such as height or width. To do any math operation with these types of returned values, you’ll need to convert them to numbers. You can do this with parseInt. If you do not use parseInt, your attempts at addition will instead result in string concatenation. The example below shows how to use parseInt with a returned CSS value to get the numerical equivalent.

var itemWidth = $("#item").css("width");
itemWidth = parseInt(itemWidth);
var distance = itemWidth + $("#item").getLeft();
console.log("The total distance from the left is: " + distance);

There are two ways to set styles on an element. You can set a property/value pair or a string of values delimited by curly braces and quoted. By enclosing the curly braced text we can pass in the complex CSS definitions as a string. At parse time, ChocolateChip removes the curly quotes and applies the CSS definition to the element:

// Example of property/value pair:
$("p:first-of-type").css("color", "red");

// Example of string enclosed in curly braces and quotes:
$$("li.members").forEach(function(members) {
   members.css("{ color: red; background-color: orange; font-size: 24px; font-weight: bold; }");

For versions 1.0.7 and earlier ChocolateChip uses the following two methods to get and set styles:

ChocolateChip has two methods for dealing with style. They are:

  1. $.style()
  2. Element.css()

$.style() takes two arguments: the element whose style you want, and the style you want:

$.ready(function() {
	var p = $("p:first-of-type");
	var pColor = $.style(p, "color");
	console.log("The text color is: " + pColor);

Setting an element’s style is easy using the Element.css() method. This method takes as its argument any valid CSS property/value pairs. By default this method adds the CSS to whatever is already defined on the element. If you want, you can pass an option second parameter of true. This will force the method to replace whatever inline styles the element might have with the styles you are passing in.

$.ready(function() {
	var p = $("p:first-of-type");
	var styles = "font-weight: bold; background-color: red; color: gold;";
	// This will append the new CSS onto the paragraph tag.
	// In contrast, this will replace whatever other styles might be inline on the paragraph with the styles being applied.
	p.css("font-size: 24px; text-shadow: 0 1px #fff; color: #000;", true);

As you can see in the above examples, you can assign the CSS to a variable and pass that in, or you can define the CSS in the method itself, your choice.

Attack of the Clones

Comments Off on Attack of the Clones

Cloning Nodes is Legal!

ChocolateChip provides several methods for dealing with nodes. These are:

Makes a copy of the element.
Deletes all of an element’s child nodes.
Deletes an element.
Wraps an element with the supplied markup.
Removes the markup containing an element, leaving the element in the document.
Replaces one element with another.



The Element.clone() method creates a copy of an element. If a boolean value that evaluates to true is passed, the element will be copied along with all of its child nodes. And if a false value is passed in, the method copies only the element, ignoring its child nodes.

<p>This is a paragraph.</p>
$.ready(function() {
    // This will clone the node with its child node, which is a text node.
    var p1 = $("p").clone();
    // This will output "This is a paragraph"
    // -1 will evaluate as a false boolean.
    // This will result in only the barebones p tag being cloned, not its content.
    var p2 = $("p").clone(-1);
    // This will not output anything since p2 has no child nodes.


The Element.empty() method will delete all child nodes from the element

<p>This is a paragraph.</p>
$.ready(function() {
    // This will remove the text from the above paragraph.


This method completely deletes a node from the document. Before deleting the element, it sets any events on the element to null. If you know what events you have bound on that element, you should probably use the Element.unbind() method to remove them before removing the element. That way your events are completely eradicated.

<p>This is a paragraph.</p>
$.ready(function() {
    // Delete the above paragraph from the document:


The Element.wrap() method wraps the element in the supplied markup. This is similar to the outerHTML method, except that it outputs true DOM nodes. In order to accomplish this, the method clones the node along with all of its children. It then creates the new markup to wrap around the node and inserts the node inside of the new markup. Then it replaces the node in the document with this newly wrapped node. This means that if you had bound and events to the original node, you will need to reattach them after wrapping. If you intend to do a lot of wrapping/unwrapping, and maintain event binding, then you should use event delegation by bind the events to the parent of the elements you intend to wrap or unwrap and capture the events during the bubbling phase. See the entry “Handing Events” for examples of this technique.

<p>This is a paragraph.</p>
$.ready(function() {
    // This will wrap the above paragraph in this div tag:
    $("p").wrap("<div id="paragraphWrapper"></div>");


The Element.unwrap() method removes the parent element from an element. To do this, it clones the node, then replaces the parent node with the cloned node. As with the Element.wrap() method, any bound events will be removed, but you can use event delegation to avoid this problem.

<div id="paragraphWrapper"><p>This is a paragraph.</p></div>
$.ready(function() {
    // This will remove the div surrounding the above paragraph:


The $.replace() method replaces one element with another. The first argument is the element you want to replace with. The second argument is the element you want to replace. As with the Element.wrap() and unwrap methods, any bound events will be removed, but you can use event delegation to avoid this problem.

<p>This is a paragraph.</p>
$.ready(function() {
    var divTag = $.make("<div id="replacementNode">A new div here.</div>");
    // This will replace the p tag with the newly created div tag:
    $.replace(divTag, $("p"));

Ajax and JSON

Comments Off on Ajax and JSON

ChocolateChip provides method for AJAX updates and JSON data binding.

A method to perform basic HttpRequests
A method to perform JSON data binding.



The Element.xhr() method provides a way to update parts of a document with dynamic content pulled from another external document. This would normally involve document fragments, but could also be a complete document, depending on what your needs are. The If no parameters are passed, the Element.xhr() method replaces the content of the target element with the content of the requested document.

<p id="update">Old text here.</p>
$(function() {
    // This will replace the content of the paragraph above with the content of the requested document.

The Element.xhr() method can also receive and object literal of options to execute depending on the success of the HttpRequest. These are successCallback and errorCallback. The successCallback allows you to do something after the successful insertion of the new content. The errorCallback allows you to do something when HttpRequest fails. You can provide both, either one or none. Here’s an example of how to provide for both:

<p id="update">Old text here.</p>
<p id="update-message"></p>
$(function() {
    /* This will replace the content of the paragraph above with the content of the requested document. If the script is successful, it will execute the successCallback, and if it is not, it will execute the errorCallback.
    $("#update").xhr("../data/newUpdate.html", {
        successCallback: function() {
            $("update-message").text("The update was successful!");
        errorCallback: function() {
            $("update-message").text("There was a problem retrieving the requested file.");


The Element.xhrjson() method provides a way to do rudimentary data binding with JSON. You do this by passing in the URI for the JSON document you want to bind to, followed by an object literal that defines which elements of your document get mapped to which values of the JSON object. The JSON document can be created and updated dynamically on the server. That way, each time your document requests it, the bound elements in your document will be updated with the current data. It’s a good idea to have some default values in your document in case there is a problem retrieving the JSON fie.

In the example below, we are binding JSON values to the corresponding element ids in a document:

Here is a json data file named data.html:

	'firstName': 'Robert',
	'lastName': 'Biggs',
	'role': ' and the author of ChocolateChip', 
	'job': ' front-end developer'

Here is a section of HTML with some default values that we wish to replace with the values from the json file:

<div id="content"><span id='firstName'>Joe</span> <span id='lastName'>Bodoni</span> is a <span id='job'>great waiter at a restaurant downtown</span></div>

And here’s the JavaScript to get the JSON file using $.xhrjson():

$(function() {
    $("#content").xhrjson("data.html", {
            "firstName": "#firstName",
            "lastName": "#lastName",
            "job": "#job"

Update Nov 19, 2010

As of version 1.0.7, ChocolateChip has a $.template() method for allowing quick and simple JavaScript-based templates on the client side. This is basically a repurposing of John Resig’s ( JavaScript Micro Template framework. It’s a very small amount of code that provides the ability to create complex templates with ease.

Here’s an example of a typical template:

<script id="template_1" type="text/jsmt">
		<% for (var i = 0; i < users.length; i++) { %>
			  <p>Name: <strong><%= users[i].fname %></strong> <em><%= users[i].lname %></em></p>
		<%  } %>
<div id="template_1_output"></div>

First thing, notice that the JavaScript template is inserted where it the data will be output. This is not a requirement. The template can be anywhere in the document. It doesn’t matter. What matters is that the script have a unique ID so that you can get it through a DOM query and that it have a special MIME type, which is “text/jsmt.” Jsmt stands for JavaScript Micro Template, obviously there is no browser that knows what a script of type jsmt is, so browsers don’t know how to parse and display the contents of the script tag. That means none of the html will be rendered. This is not a bug in browsers, this is how they are supposed to function. If you look at the contents of the script tag you will see we have some HTML tags for defining the template’s structure and we have JavaScript enclosed in and tags. The first set, is for normal JavaScript code. The second set of tags, is used for processing a variable in the template. If you’ve used ASP or JSP in the past, you will recognize these tags.

After the $.template method processes the script tag, it outputs the result. It’s your job to decide where you want to output the result to. You can store it in a variable and out put it later, or immediately. So, from our previous example, to process the template, we use the $.template() method:

   // Process the template of ID "template_1" with JSON data in the variable "data".
    var r = $.template("template_1", data);
    // insert the results of the parsed template into the div with id "template_1_output."

We could also perform conditional checks inside the tags before outputting the data:

<script type="text/jsmt" id="jsmt_list_items">
	<% people.each(function(name) {
                // Only output names with a y in them:
		if (/y/.test(name)) { %>
		<li><%= name %></li>
	 <% }
	}); %>

Update Dec 23, 2010

As of version 1.0.8, ChocolateChip offers two methods to enable the HTML5 dataset API for browser versions that support it. For those that do not it has a fallback using normal DOM get and set attribute methods.
A method add or retrieve dataset values
A method to remove a dataset from and element.

According to the dataset API in HTML5, any element can have datasets indicating information relative to that element. a dataset value always begins with “data-“. Here’s and example of an element with datasets:

   <li data-first-name="John" data-last-name="Doe" data-occupation="teacher">John Doe<li>
   <li data-first-name="Sam" data-last-name="Smith" data-occupation="doctor>Sam Smith</li>

Using we can get any of the dataset values in this way:

console.log("John's occupation is: " + $("li:first-of-type").data("occupation"));

Similarly, we can set a dataset value as follows:

(function() {
   var personnelHeight = [ "5f8n", "5f10n", "6f0n" ];
   var heightnum = 0;
   $$("li").each(function(item) {"personnel-height", personnelHeight[heightnum]);

To remove a dataset, use the Element.removeData() method:

(function() {
   $$("li").each(funciton(item) {
      item.removeData("first-name"); /* Removes data-first-name from each list item. */

Special Tools for Special Needs

Comments Off on Special Tools for Special Needs

ChocolateChip has several utility methods that enable you to do useful things. These are:

This method can take two arguments: the object to extend and the properties to extend it with. If only properties are passed, they are added directly to the $ object to extend ChocolateChip itself. The properties are passed as an object literal of key/values pairs.
This method imports the indicated script into the document by attaching it to the head tag. It accepts a valid URI to the script.
If the mobile browser is not in standalone mode, meaning that the user has not yet installed the Web app on a mobile device, this method hides the browser address bar by slightly scrolling the page to force the addressbar out of view. Until the user actually adds the mobile Web app to the mobile device, this method will help make the online browser use of the Web app feel mofe like an installed app.

Using $.extend()

	growl : "Woof!",
	bark : function(msg) {
		if (!msg) {
			msg = this.growl;
$(function() {
	$.growl = "Bow wow! Bow wow!";
	/* This outputs:
	Bow wow! Bow wow!

Using $.importScript()

If you need to dynamically import a script for whatever reason, you can use this method to do so. It inserts the script into the head tag, at which point the browser immediately parses the scripts and executes it. Simply pass in a valid URI for the script:

$(function() {

Using $.hideURLbar()

You want to execute the $.hideURLbar() method whenever the user does something that might cause the browser addressbar to remain in view, such as when the user navigates to annother page, or when the user changes the orientation of the device. To hide the addressbar, simply invoke the method after whatever code might cause the scrollbar to appear:

$(function() {
	$("#aboutButton").bind("click", function() {
		/* This code adds a class to the about panel, causing it to slide into view. */
		// After scrolling the panel into view, make sure the addressbar is not showing.

From version 1.0.7, ChocolateChip offers the following four methods: $.delay(), $.defer(), $.enclose(), and $.compose().


This method enables the delayed execution of a function. $.delay() takes two arguments, a function and an integer indicating how long to wait before executing the function:

$.delay(function() {
     console.log("This message is delayed by two seconds.");
}, 2000);


The $.defer() method cause the execution of a function to wait until the callstack is clear. This means that regardless of where this is in a block of code, it will be executed after all other code.

 $.defer(function() { 
     console.log("This will be executed after all the other code."); 
console.log("This will be executed before the code before it."); 


This method enables you to enclose a method inside another method so that you can do something before and after the enclosed method’s execution. It takes two arguments, the function to enclose and the function that encloses it. Below you can see that the function “hello” gets passed in the the enclosing anonymous function as the term func, which allows us to envoke it as func(“Stan”) with concatenation before and after it:

var hello = function(name) { return "Hello, " + name + "!"; };
hello = $.enclose(hello, function(func) {
     return "Before I said, \"" + func("Stan") + "\" I thought about it for a while.";


This method enables the ability to pass one function as an argument of another, building up a chain of passed function arguments. When multiple functions are passed as arguments, they are passed in as arguments from the right to the left, so that the last argument becomes the argument for the function preceding it, etc.

var greet = function(name) { return "Hi there, " + name; };
var exclaim  = function(statement) { return statement + "!"; };
var remark = function(remark) { return remark + " You know I'm glad to see you."; };
var welcome = $.compose(remark, greet, exclaim);
console.log(welcome('Jeff')); // => Hi there, Jeff! You know I'm glad to see you.

Besides these, there are a couple of others. First off, ChocolateChip automatically outputs a class of “portrait” or “landscape” on the body tag when the mobile device’s orientation changes. You just have to write your CSS to be aware of that. Something like this would work:

body.portrait > article {
	background-color: green;
	color: red;
body.landscape > article {
	background-color: red;
	color: green;

Customize the aliases for ChocolateChip

In case you are really, really want to use some other library with ChocolateChip, and you’re using one that also uses $ and $$, ChocolateChip will automatically reassign its $ and $$ methods to __$ and __$$ respectively. If you don’t want to use these either, you can assign them to whatever other aliases you wish. To make this all work, though, you’ll need to import the other library before ChocolateChip, otherwise ChocolateChip will clobber the $ and $$ of the other library. To reassign the default ChocolateChip aliases, do so in a $.ready block as follows:

<script src="someOtherLibrary" type="text/javascript"></script>
<script src="chocolatechip-1.0.6.js" type="text/javascript"></script>

<script type="text/javascript">
$(function() { = window.__$;
    window.CC = window.__$$;
    // Now you can use cc and CC for ChocolateChip's $ and $$ while using the $ and $$ of the other library.


If you change the reference to $ and $ and you have any external ChocolateChip scripts that use $, you will need to update those as well or you’ll get an error because $ and $$ will not point to the ChocolateChip versions. Although you can change ChocolateChip’s global alias to whatever you want, ChocolateChip will continue to use $ internally.

Device detection

ChocolateChip also provides a number of device tests so that you can write custom code for different devices. The test return true or false. Here is what’s available:

  1. iphone
  2. ipad
  3. ipod
  4. android
  5. webos
  6. blackberry
  7. online
  8. standalone

Here’s an example of device detection:

if (!$.iphone) {
	alert("This app only works with the iPhone.");
if (!$.standalone) {
	alert("Please install this app on your homescreen by pressing the plus icon in the toolbar below.")
if (ipad) {

Update Dec 23, 2010

As of version 1.0.8, ChocolateChip offers the following two methods:

A method get the offset top of an element relative to the document’s top.
A method to get the offset left of an element relative to the documents left.

These two methods return their position as integers without any length identifiers:

var elem = $("#favItem");
var elemPos = "top: " + elem.getTop() + "px; left: " + elem.getLeft() + "px;";
console.log("The element's position is: " + elemPos);

New in version 1.2.0:

Object Extension:

Just as you can use forEach() or each() on an array, ChocolateChip also provides a convenient way to iterate over an object using Object.each(). Like each() on an array, you can access the key and value of the object. As with the array version, you can name these two arguments whatever you want. The first argument will always be the key and the second, the value”

var obj = {"i-1": "item 1", "i-2":"item 2", "i-3":"item 3", "another-one":"item 4", "something-else":"item 5"};
obj.each(function(key, value) {
    $("ol").append("<li>" + value + "</li>");

This will output:

   <li>item 1</li>
   <li>item 2</li>
   <li>item 3</li>
   <li>item 4</li>
   <li>item 5</li>

Effective Use of Selectors

Comments Off on Effective Use of Selectors

A Feast of CSS3 Selectors for You

ChocolateChip uses the DOM’s built-in selector engine to get elements. Because this uses CSS3 selectors, you can use any combination of CSS3 selectors to get an element. This is especially important because a properly crafted CSS3 can help you avoid having to do other filtering tasks later to find the exact element that you wanted. By using a carefully constructed selector, you managed to pluck it out of the document with your first query and are ready to do something with it. Gone are the days of getting every li or p tag and checking them with JavaScript for certain conditions. Instead you can define you selector in such a way that you get a collection of the desired nodes from the start.

The W3C has a list of all the selectors that are available to use. At some point you want to read through the document carefully to fully understand how these selectors work. The barebones list is as follows:

Pattern Meaning Described in section
* any element Universal selector
E an element of type E Type selector
E[foo] an E element with a “foo” attribute Attribute selectors
E[foo=”bar”] an E element whose “foo” attribute value is exactly equal to “bar” Attribute selectors
E[foo~=”bar”] an E element whose “foo” attribute value is a list of
whitespace-separated values, one of which is exactly equal to “bar”
Attribute selectors
E[foo^=”bar”] an E element whose “foo” attribute value begins
exactly with the string “bar”
Attribute selectors
E[foo$=”bar”] an E element whose “foo” attribute value ends exactly
with the string “bar”
Attribute selectors
E[foo*=”bar”] an E element whose “foo” attribute value contains the
substring “bar”
Attribute selectors
E[foo|=”en”] an E element whose “foo” attribute has a
hyphen-separated list of values beginning (from the left) with “en”
Attribute selectors
E:root an E element, root of the document Structural pseudo-classes
E:nth-child(n) an E element, the n-th child of its parent Structural pseudo-classes
E:nth-last-child(n) an E element, the n-th child of its parent, counting
from the last one
Structural pseudo-classes
E:nth-of-type(n) an E element, the n-th sibling of its type Structural pseudo-classes
E:nth-last-of-type(n) an E element, the n-th sibling of its type, counting
from the last one
Structural pseudo-classes
E:first-child an E element, first child of its parent Structural pseudo-classes
E:last-child an E element, last child of its parent Structural pseudo-classes
E:first-of-type an E element, first sibling of its type Structural pseudo-classes
E:last-of-type an E element, last sibling of its type Structural pseudo-classes
E:only-child an E element, only child of its parent Structural pseudo-classes
E:only-of-type an E element, only sibling of its type Structural pseudo-classes
E:empty an E element that has no children (including text
Structural pseudo-classes
an E element being the source anchor of a hyperlink of
which the target is not yet visited (:link) or already visited
The link pseudo-classes
an E element during certain user actions The user action pseudo-classes and 2
E:target an E element being the target of the referring URI The target pseudo-class
E:lang(fr) an element of type E in language “fr” (the document
language specifies how language is determined)
The :lang() pseudo-class
a user interface element E which is enabled or
The UI element states pseudo-classes
E:checked a user interface element E which is
checked (for instance a radio-button or checkbox)
The UI element states pseudo-classes
E::first-line the first formatted line of an E element The ::first-line pseudo-element
E::first-letter the first formatted letter of an E element The ::first-letter pseudo-element
E::before generated content before an E element The ::before pseudo-element
E::after generated content after an E element The ::after pseudo-element
E.warning an E element whose class is “warning” (the document
language specifies how class is determined).
Class selectors
E#myid an E element with ID equal to “myid”. ID selectors
E:not(s) an E element that does not match simple selector s Negation pseudo-class
E F an F element descendant of an E element Descendant combinator
E > F an F element child of an E element Child combinator
E + F an F element immediately preceded by an E element Adjacent sibling combinator
E ~ F an F element preceded by an E element General sibling combinator

Out of the above selectors, the attribute selectors and the structural pseudo-classes offer you a whole lot of power in selecting otherwise difficult to define elements. You can get elements according to their attributes or the values of their attributes. You can get elements based on their relation to their siblings. You can even get an element based on whether it’s empty or not or by excluding elements of a certain type.

OK, time for some practical examples. One of the most common visual styling needs is zebra striping of rows or list. With CSS3 selectors this is easy. You have several ways to do this:

li:nth-of-type(even) – all even list items
li:nth-of-type(odd) – all odd list items
li:nth-of-type(10) – the 10th list item

Similarly, to we can use the nth-child selector to get the children of an element using the same notation. Here we’re going to to define a repeating set of four paragraphs. The first selector targets the first paragraph in that set, etc.

section:nth-child(4n+1) – first paragraph out of a set of four
section:nth-child(4n+2) – second paragraph out of a set of four
section:nth-child(4n+3) – third paragraph out of a set of four
section:nth-child(4n+4) – fourth paragraph out of a set of four

To get the 9th child out of a repeating set of 10, you can use this:
section:nth-child(10n-1) – would get 9th, 19th, 29th, 39th, etc.

As I mentioned, you can also get an element based on whether it’s empty, or you can exclude all elements of a particular type.

p:empty – a paragraph with no child nodes
:not(p) – all nodes except those of type “p”
p:not(p:empty) – all p tags except those that are empty
p:not(p[class]) – all p tags that do not have a class attribute.

From the above examples it should be clear the value of creating efficient selectors when you need to access elements in a document. Constructing a proper selector can eliminate the need for post filtering with JavaScript. This in turn will make your app faster and more responsive for the user.

Difference Between :first-child and :first-of-type

    <p>The first paragraph</p>
    <div>The first div</div>
    <div>The last div</div>
    <p>The last paragraph</p>

One last thing, you should be aware of the difference between :first-child and :first-of-type. If you look at the above markup you’ll see there are several paragraph tags and divs. You might think that you could use $("div:first-child") to get the first div. You’d be wrong. In the above code the first div is not the first child, it’s the second child. As such you would not get anything. To get the first div you’d need to use $("div:first-of-type). But if you really wanted the first child, regardless of what type of tag it is, you could use $("section").first() or $("section").firstElementChild. The same would apply when getting the last div or the last child in the above example. $("div:last-child") would not return the last div. $("div:last-of-type") would. To get the last child regardless of the tag, you could use $("section").last() or $("section").lastElementChild.

Older Entries Newer Entries