jQuery for Complete Beginners: Part 2

Posted in Coding, Tutorials • Posted on 19 Comments

Welcome to part 2 of jQuery for beginners. In the first part we looked at how to add jQuery to our pages and also looked at how jQuery selects elements on the page before finally animating a div. In this lesson we are going to look purely at how to select elements through their relationship with the element we are already interacting with. This may seem complicated, but it’s in fact very straightforward.

Essentially, if we have already selected an element, how can be traverse the page to find its parent element? We could just use another selector, but there are much better ways to do it. For example, take this HTML code:

<div>
<h2>A header with <a href="http://www.1stwebdesigner.com">a link</a> inside.
<p>A paragraph in the div</p>
</div>

And then using jQuery we had already selected the h2 element:

$('h2').

How would we then select the div? We might just do a different selector:

$('div'). 

While this works fine in this case, imagine a much more complex site. Having rogue and vague selectors like that are not going to help. It would also mean giving other elements unnecessary ‘hooks’, such as an ID, just for the purpose of our JavaScript. In reality, jQuery makes it much easier:

$('h2').parent(); //this would select the div.

This is the cusp of this lesson – to learn how we can be ‘sneaky’ with our code to allow us to do less actual selecting and learn to work with what we already have.

Say now, instead of selecting the h2’s parent, we want to find its children, which in our case is the link. We could go back to CSS:

$('h2 a');

But in reality, for reasons not worth divulging into at this moment, that takes a lot of work on jQuery’s part. What if, instead, jQuery provided a method to do the same thing? Well, it does!

('h2').children(); //selects the link element

But what if the h2 element had more than one child element? jQuery actually allows us to pass in a selector to the children() function to be more specific:

$('h2').children('a'); //selects all children of the h2 that are anchor elements.

In our next example, let’s have a quick unordered list:

<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>

Of course to select all the list items is as simple as:

$('li');

Or you could use our new function:

$('ul').children();

Generally which one you use depends on the situation on your page. For example, if I had two lists, one ordered (

    • ) and only wanted to select the list items from one of those, I would use the latter of the two methods above.
  1. ) and one unordered (

If we want to interact with a specific item in that list, we can use another jQuery function, eq():

$('li').eq(2); //selects list item 3

Please note that it selects the 3rd item. This is because in most languages, the index is zero based. This means it starts from 0. So in our list, we have 5 items, the first of which you could call the ‘0th item’. If you struggle to remember this, just remember that you need to subtract one from the number you would usually use. Don’t worry, a few hours of coding and it will sink in.

Before we go any further it’s important for you to realise that one of the key principles of jQuery is its ‘chainability’. This means that functions can be run one after the other, or chained:

$('ul').children('li').eq(3).animate({...});

The above code takes the following steps:
1. $(‘ul’) => Select all unordered lists on the page.
2. children(‘li’) => select all children of the lists that are list items.
3. eq(3) => select the 2nd list item from each list.
4 animate({…}) => animate that specific item. We covered basic animations in the last lesson.

Whilst the children() function only finds the immediate descendants of the selected item, jQuery provides a way to delve deeper. Going back to our HTML code we used much earlier:

<div>
<h2>A header with <a href="http://www.1stwebdesigner.com">a link</a> inside.</h2>
<p>A paragraph in the div</p>
</div>

If I had the following selector:

$('div');

And now want to select the anchor element within the h2, you might think, correctly, to do this:

$('div').children('h2').children('a);

Generally, as a rule of thumb, when you use the same function twice in a row, there is a better way to do it. And of course, there is, using jQuery’s find() method. Using this, the above line of code becomes:

$('div').find('a');

The find function does not stop after the first descendants of the div element. It keeps going. It finds the immediate children, then the children of those children, and so on. Basically, find() searches all elements within the selected element, no matter how many levels down they are.

Next we have four basic functions to look at that allow us to select an element’s siblings. These are elements on the same level as the one currently selected. In our above HTML, the h2 & p elements would be siblings. Take a look at the following functions:

$('h2').next(); //selects the next sibling (the paragraph)
$('h2').nextAll(); //selects all the siblings after it.
$('p').prev(); //selects the previous sibling (the h2)
$('p').prevAll(); //selects the previous siblings

As you can see all of them are pretty simple, and handy if you need to jump along to the next element.

The final function we are going to look at is the siblings() function. Lets have a new block of HTML code to work with:

<p>A paragraph</p>
<h2>A heading</p>
<img src="somepic.jpg" alt="A picture">
<h1>A bigger heading</h1>

From the first paragraph, we could use nextAll() to select all its siblings (as it’s the very first sibling):

$('p').nextAll();

But if we were at the h2 element, how could we select all its siblings? Easy:

$('h2').siblings();

The siblings() function can also take a selector as an argument:

$('h2').siblings('p') //selects just the siblings that are paragraphs

Just before I end, as a quick side note, last lesson, we spoke about including your jQuery at the very bottom of the page, before the final </body> tag. However, you can include it in the header, or anywhere else in fact, if you add this line first:

$(document).ready(function() {...});

What that does is makes sure the code you write runs after all the page content is loaded – otherwise you could be manipulating elements that have yet to load. ALl you do is wrap your jQuery in the above function:

$(document).ready(function() {
//all your jQuery code goes here like normal
});

That only applies if you add your code anywhere except before the closing </body> tag.

The End

I hope you’ve enjoyed our brief foray into the world of jQuery selectors. In the next lesson we will get some cool stuff going and look at sliding elements in and out. We will also look at events and responding to, for example, an element being clicked. As always if you have any questions please feel free to leave a comment and I’ll answer them next time.

4 Written ArticlesWebsite

Jack Franklin is a 17 year old budding web designer & developer living in Cornwall, England who enjoys messing with HTML, CSS, PHP & Javascript. Away from the desk, Jack enjoys badminton, football & snooker.

19 Comments Best Comments First
  • niblr

    Friday, April 23rd, 2010 18:32

    15

    Great tutorial for beginners, thanks a lot!

    Just a little little thing:
    When you introduce the siblings(); function
    “A heading” should be with the /h2 closing tag.
    …but I think everyone knows that ;)

    cheers

    +1
  • Fatih

    Friday, March 26th, 2010 23:22

    4

    3. eq(3) => select the 2nd list item from each list.

    Did you just mention that indexes are zero based? So this means it would select the 4th list item, or did I miss something?

    +1
  • nam124084

    Sunday, March 28th, 2010 17:11

    9

    Hi, sorry but i have one quesiton :) .when i read our webpage , i see our image is load very beautiful when scroll down ( something like … uh ..image ‘s opacity from 0 to 1 ) . how did you do that ? . jquery ? or plugin ?

    +1
    • Dainis Graveris

      Thursday, April 1st, 2010 17:27

      12

      it is lazy load wordpress plugin to save bandwidth and not load images which are not viewed :)

      0
  • Nikola Dadić

    Monday, April 19th, 2010 11:05

    13

    We are waiting for new tutorial!

    +1
    • Saad Bassi

      Monday, April 19th, 2010 12:08

      14

      Will be published tomorrow.:)

      +1
  • shruti

    Monday, April 25th, 2011 07:59

    16

    hi,
    very nice tutorial for the beginners. thanks a lot . one question. i tried to do this

    $(‘h2′).siblings().animate({‘width': ‘400px’}, 1000);

    for these html tags:

    A heading
    A paragraph

    A bigger heading

    this is working fine. But when i changed it to:

    $(‘p’).siblings().animate({‘width': ‘400px’}, 1000);

    it is working for all the sieblings but not for tag.
    Is it necessary to give the above mentioned tag on only?

    it is not takiing for the tag

    +1
  • fase

    Friday, March 2nd, 2012 07:46

    19

    i am a beginner in jquery this blog is very helful for me

    +1
  • Slobodan Kustrimovic

    Saturday, March 27th, 2010 16:12

    6

    @larry – I don’t see a need for knowing advanced javascript to start learning jQuery, all you need is basic javascript knowledge.

    0
    • Larry

      Saturday, March 27th, 2010 17:46

      7

      Untill you come across bugs in jQuery.. =P

      0
  • Nishant

    Saturday, March 27th, 2010 00:59

    5

    Hey jack, very nice tut. Thanks for this.

    0
  • Alfredo

    Saturday, March 27th, 2010 04:18

    2

    Thanks for this tutorials man, cant wait for the next one , keep them up

    cheers.

    0
  • Larry

    Friday, March 26th, 2010 23:08

    3

    Great post :) Tho I still think people new to jQuery should first start getting into JavaScript on a more advanced level..

    0
  • Bryan

    Monday, March 29th, 2010 16:03

    10

    Great tutorial. I love it when people go back to the basics. I understand if you’ve used it for a while these kinds of things seem like a given, but tutorials like this are really helpful for newbs like me. Thanks

    0
  • Elving

    Saturday, March 27th, 2010 23:25

    8

    The great think about jquery is that is so easy to learn, you only need basic JavaScript understanding to use it. But if you want to develop plugins and complicated stuff THEN you should learn some goo JavaScript. Thanx for the awesome tutorial!

    0
  • Vinod

    Thursday, November 17th, 2011 06:05

    17

    Awesome!!
    Please give link to the next part in this article itself.. I am finding it difficult to find the next part :(
    Or did i miss some thing?

    0
  • Tuanka

    Wednesday, March 31st, 2010 12:20

    11

    Greate tutorial, keep going!

    0
  • Geeee

    Saturday, March 27th, 2010 01:20

    1

    Ohh I wanted to learn about it :) thanks for the good post :)

    0
  • Rajdev

    Monday, January 16th, 2012 12:58

    18

    The find function does not stop after the first descendants of the div element. It keeps going. It finds the immediate children, then the children of those children, and so on. Basically, find() searches all elements within the selected element, no matter how many levels down they are.

    -1
  • fase

    Friday, March 2nd, 2012 07:46

    19

    i am a beginner in jquery this blog is very helful for me

    +1
  • Rajdev

    Monday, January 16th, 2012 12:58

    18

    The find function does not stop after the first descendants of the div element. It keeps going. It finds the immediate children, then the children of those children, and so on. Basically, find() searches all elements within the selected element, no matter how many levels down they are.

    -1
  • Vinod

    Thursday, November 17th, 2011 06:05

    17

    Awesome!!
    Please give link to the next part in this article itself.. I am finding it difficult to find the next part :(
    Or did i miss some thing?

    0
  • shruti

    Monday, April 25th, 2011 07:59

    16

    hi,
    very nice tutorial for the beginners. thanks a lot . one question. i tried to do this

    $(‘h2′).siblings().animate({‘width': ‘400px’}, 1000);

    for these html tags:

    A heading
    A paragraph

    A bigger heading

    this is working fine. But when i changed it to:

    $(‘p’).siblings().animate({‘width': ‘400px’}, 1000);

    it is working for all the sieblings but not for tag.
    Is it necessary to give the above mentioned tag on only?

    it is not takiing for the tag

    +1
  • niblr

    Friday, April 23rd, 2010 18:32

    15

    Great tutorial for beginners, thanks a lot!

    Just a little little thing:
    When you introduce the siblings(); function
    “A heading” should be with the /h2 closing tag.
    …but I think everyone knows that ;)

    cheers

    +1
  • Nikola Dadić

    Monday, April 19th, 2010 11:05

    13

    We are waiting for new tutorial!

    +1
    • Saad Bassi

      Monday, April 19th, 2010 12:08

      14

      Will be published tomorrow.:)

      +1
  • Tuanka

    Wednesday, March 31st, 2010 12:20

    11

    Greate tutorial, keep going!

    0
  • Bryan

    Monday, March 29th, 2010 16:03

    10

    Great tutorial. I love it when people go back to the basics. I understand if you’ve used it for a while these kinds of things seem like a given, but tutorials like this are really helpful for newbs like me. Thanks

    0
  • nam124084

    Sunday, March 28th, 2010 17:11

    9

    Hi, sorry but i have one quesiton :) .when i read our webpage , i see our image is load very beautiful when scroll down ( something like … uh ..image ‘s opacity from 0 to 1 ) . how did you do that ? . jquery ? or plugin ?

    +1
    • Dainis Graveris

      Thursday, April 1st, 2010 17:27

      12

      it is lazy load wordpress plugin to save bandwidth and not load images which are not viewed :)

      0
  • Elving

    Saturday, March 27th, 2010 23:25

    8

    The great think about jquery is that is so easy to learn, you only need basic JavaScript understanding to use it. But if you want to develop plugins and complicated stuff THEN you should learn some goo JavaScript. Thanx for the awesome tutorial!

    0
  • Slobodan Kustrimovic

    Saturday, March 27th, 2010 16:12

    6

    @larry – I don’t see a need for knowing advanced javascript to start learning jQuery, all you need is basic javascript knowledge.

    0
    • Larry

      Saturday, March 27th, 2010 17:46

      7

      Untill you come across bugs in jQuery.. =P

      0
  • Nishant

    Saturday, March 27th, 2010 00:59

    5

    Hey jack, very nice tut. Thanks for this.

    0
  • Fatih

    Friday, March 26th, 2010 23:22

    4

    3. eq(3) => select the 2nd list item from each list.

    Did you just mention that indexes are zero based? So this means it would select the 4th list item, or did I miss something?

    +1
  • Larry

    Friday, March 26th, 2010 23:08

    3

    Great post :) Tho I still think people new to jQuery should first start getting into JavaScript on a more advanced level..

    0
  • Alfredo

    Saturday, March 27th, 2010 04:18

    2

    Thanks for this tutorials man, cant wait for the next one , keep them up

    cheers.

    0
  • Geeee

    Saturday, March 27th, 2010 01:20

    1

    Ohh I wanted to learn about it :) thanks for the good post :)

    0

Comments are closed.

54.196.168.236 - unknown - unknown - US