[Update: All the html and formatting turned into a total cluster fuck once I saved it. I am too lazy to fix it now. I will figure this out for next week :P]
Last week I started learning jQuery and had decided to do one chapter a week. So, here is the second installment. This week is all about selecting elements in the dom. Last week I just read through the entire chapter and then started blogging and it didn't really turn out great. This week I am writing as I read. We'll see how this goes. The pattern for this post is going to be in the form of a series of Problems and Solutions. You can test your jquery skills by coming up with a solution without looking at the answer. So, here we go.
Problem:
Category
<ul id="nav">
<li>Anchor 1</li>
<li>Anchor 2</li>
<li><span>Anchor 3</span></li>
</ul>
Given this html, select the anchor elements within each list item.
Solution: jQuery('#nav li > a')
Problem:
<div id="content">
<h1>Main title</h1>
<h2>Section title</h2>
<p>Some content...</p>
<h2>Section title</h2>
<p>More content...</p>
</div>
Given the above html, select all h2 which come right after h1.
Solution: jQuery('h1 + h2') - I have to say this is non intuitive.
Problem:
<ol>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
<li>Fourth item</li>
</ol>
From above, select the 3rd <li>. Bonus, select <li> at even indices.
Solution: jQuery('ol li:first')
Bonus: jQuery('ol li:even')
Problem:
<li>
<input type="text" />
<input type="password" />
<input type="button">Enter</input>
<input type="text" />
</li>
Select elements of type "text"
Solution: jQuery(':text')
Those were very basic ways in which you can select elements in a dom. Once things get complicated, the best thing to use is the filter method.
Ex:
<li style="width:100px">First item</li>
<li style="width:200px">Second item</li>
<li style="width:300px">Third item</li>
<li style="width:400px">Fourth item</li>
Let's say you want to select li whose width is between 150 and 350. Here is what you would do:
jQuery('li').filter(function() {
width = jQuery(this).width();
return width > 150 && width < 350;
});
filter basically applies the function to every element returned by the selector (in this case jQuery('div)) and returns a new list whose elements match the function.
Now, let's say you want to use this in multiple places. There is a slick way to create a new custom filter that selects div with the width between 150 and 350 and use it wherever you want. So, to do that,
jQuery.expr[':'].customWidth = function(elem, index, match) {
width = jQuery(elem).width();
return width > 150 && width < 350;
};
Now, once you have defined that, you can use it like you use inbuilt filters like :text, :radio etc.
So,
jQuery('li:customWidth') should return 2 elements whose width is 200 and 300.
That's it for the day. I think I will remember lot more from this week because I was writing, playing with it as I was reading. See you next week with third chapter!