jQuery for Complete Beginners: Part 2

Facebook

Twitter

Google+

Pinterest

+

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:

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.

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.

) 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:

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:

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:

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.

Facebook

Twitter

Google+

Pinterest

+

The Community of Web Design Professionals

"It's our personal mission to make sure you become the best web design professional." -James, CEO / Co-Founder

Valuable ideas once a week

Hi there. Just wanted to share my story with you guys. I signed up with Awesome Web on 30th Sept and today is 18 Oct and I have got 8 Enquiries since then and got 3 clients since then as follows: 1. Logo Design >>> $85 2. Wordpress Design >>>$400 3. Wordpress Design >>>$450 So I think its a great ROI>>> $935 from just $17!!!

Comments

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.

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

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 ?

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!