jQuery css methods

→ Are you a new visitor? Please visit the page guidance for new visitors ←

Working with jQuery Methods

Now, it is time to see some of these methods in action. We will start by explaining the addClass() method. From the definition, this method is used to add one or more class names to selected elements. Working on our example structure, we will want to give to our body element a class of “customBody”. Remember how we select the body element ? Let’s see closer:

There ! So simple and readable. First, we select the body element and then call the addClass method. Our body element will now have that class added in the DOM.

Now, what if we want to remove that ? We will use another method that jQuery has.

If we want to eliminate from the DOM the body element (we do not want that very often, but we will want to delete other elements perhaps), we will use .remove() jQuery method in the same way we used the other ones.

Another interesting and used method is the .val() method. This is used to get the value of some DOM elements like inputs, textareas, etc. Let’s see and example:

Above, we have an input the an id (to be easy to select with jQuery), and we want to get it’s value (which is “data to be extracted” ). We select the input with the dollar selector and perform a .val() on it like this:

With jQuery we can get or set other properties and insert into DOM other elements as well. What if we want to insert right at the end of our unordered list another list element, let’s say “list item 4” ?

Beware! This selector is selecting everything that is an “ul” on the page. For our example it is working because we have only one “ul” element.

We can control the place where we add the new list by using some other methods. If you want to insert this new list item in the top of the other lists, we use another method called .prepend().

Now, the list item 4 will be in front of list item 1 in the DOM.

To go further, we can insert our list wherever we want in the ul element. Using .insertAfter() we can specify the place where we want that list to go.

Now we inserted that in the second position, right after the first child (item 1).

Good ! Jquery is so easy to understand now, is it ? 🙂

Other methods

The other css methods are used in the same way as these presented, the only thing that remains is to play with them. Jquery has a very intuitive syntax that is why, it is the most used javascript framework.

Summary

Until now, in this jQuery course we learned how to select elements that are available in the DOM, and apply methods for manipulation of structure. We also learn how to traverse the DOM for querying other elements. Stay focused for the next tutorial in which we will learn about DOM Manipulation Methods.

↠ Page 1 jQuery - css methods

Pages: 1 2

Request an article ←