ChocolateChip provides several methods working with classes

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

Element.hasClass()

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");
		}
	});
});

Element.addClass()

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) {
	item.addClass("subcategory");
});

Element.removeClass()

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

$.ready(function() {
	$$("a").forEach(function(link) {
		if (link.hasClass("external")) {
			link.removeClass("External");
		}
	});
});

Element.toggleClass()

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.toggleClass("touched");
		};
		item.bind("touchend", function() {
			item.toggleClass("touched");
		};
	});
	$$("a").forEach(function(link) {
		link.bind("touchstart", function() {
			link.toggleClass("touched", "untouched");
		};
	});
});
Advertisements