jQuery Basics Part III

Asif Ahmed

In this post we will be looking at Videos 4-6 of the jQuery for Absolute Beginners Video Series.

Video 4 and video 5 cover advanced selectors and removing and adding elements. We will be focusing on adding and deleting list elements. An example can be found here.

var i= $('#second li').size();
$('<li>' + i + '</li>').appendTo('ul#second');
$('#second li:last').remove();

Basically in the first line we create a variable and set it equal to the amount of list items in the list with id=”second”. We have to remember that “li” means list items. We can then output the value of this variable with a console.log statement to the console. The console can be viewed if you had the Firebug plugin for Firefox or you are using Chrome. Afterwards we have two functions. If we click on the anchor tag with the id=”add” we will increment the value of the variable that was the amount of list items. We then append some HTML code, which creates a new list item, to the end of the unordered list with the id=”second”. This will effectively add a list item with the correct number to the end of the second list. Again try it out here. The second function is for deleting the last list item from the second list. The code within the if statement is just to make sure that if the user clicks on “Remove List Item” more than enough times to completely remove all items from the list and then clicks on “Add List Item” we will end up with a “1” in the first list item instead of a negative number.

Video 6 covers the toggle and toggleClass methods. The toggle method is pretty straightforward. The following code can toggle a div with id of “box” on and off.

$('a').click(function() {

The following code with be able to toggle the CSS class of elements on and off.

$('a').click(function() {
$('p').click(function() {

Basically every time you click on an anchor tag it will toggle the class “border” for the box. Also every time you click on a paragraph if will toggle the class highlight for the paragraph that you clicked on. This functionality can be observed here.