Nov 30, 2009

Walking around with JQuery

Selecting, traversing, and manipulating DOM elements is relatively easy with JQuery. You can play with them and do many cool things.

Let’s start with simple selecting. We may need a list of all the images in a document. This can be achieved very easy:

Let’s hide them:

Now, if we don’t want all images but only images located in div tag we can do this:
       $("div > img").hide();
Selecting element with a specific id is very simple:
And we can obtain a list of images located in this specific div with the expression:
       $("#myId > img")
We can get a list of elements from a certain type and having a specific class. For example we can get a list of all div elements who have css class text and hide them.
       $("div .text").hide();

If we get a list of elements from another source (for example some function) and we want to obtain only the ones with a exact property we can do it with filter. In this example I’ll select all div elements and check them:

After hiding all elements we may want to show the first one. Here we have several approaches. If the circumstances are right we can just select the first element:
Of course we may want the last one:
We can get the n-th element using eq. Keep in mind that arrays start from 0.
        var n = 1; // we want the second element in reality
We can obtain all elements on a page that contain a specific text:
        $("div:contains(text)"). css("background-color","yellow");
Or we can obtain all div elements containing a specific text (text) and not specific css class:
         $("div:contains(text):not(.title)"). css("background-color","yellow");
I’ll continue with more later.

No comments:

Popular Posts