CSS Selectors and Prototype

Most JavaScript libraries provide some form of the $() function. This function is a short hand version of document.getElementById(). However, I was only recently introduced to the $$() function in Prototype. $$() takes a list of CSS selectors and returns an array of objects that match. This ends up being a much easier and more maintainable way to access elements in the DOM than giving EVERYTHING an id. Although the scope of CSS selectors in general is way to large for this tutorial, we will walk thru a simple use of the $$() function in prototype and introduce you to CSS selectors.

The Elements of a List

Let's look at the following HTML. We have created a simple ordered list with three elements.

<html>
     <body>
          <h1>To Do List</h1>
          <ol>
               <li>Finish this blog post</li>
               <li>Go car shopping with wife</li>
               <li>Cry about 401k</li>
          </ol>
     </body>
</html>

Now notice that nothing has an id. However, let's say I want to loop over my todo list using Prototype. Here's all the code I would need:

function alertItems() {
     $$('li').each(function(element) {
          alert(element.innerHTML);
     });
}

Let's take a look at that function. What Prototype is doing is getting all of the li elements in the page and returning them as an array. We then loop over the array, alerting the contents of each element. Now let's look at a little more complex example.

Multiple Lists

Let's say we have more than one list on the page (*gasp!) like the HTML below.

...
<h1>To Do List</h1>
<ol id="todo">
     <li>Finish this blog post</li>
     <li>Go car shopping with wife</li>
     <li>Cry about 401k</li>
</ol>

<h1>Completed List</h1>
<ol id="finished">
     <li>Dishes</li>
     <li>Laundry</li>
     <li>Email responses</li>
</ol>
...

Now what would happen if we reran the same function we created previously? It would give us six alerts, one for each li in both lists. But let's say we only want to loop thru the items in the second list. That's easy:

function alertItems() {
     $$('#finished li').each(function(element) {
          alert(element.innerHTML);
     });
}

All we need to do is add "#finished" to the selector in our function. Now Prototype looks for the element that has an id that equals finished and gets all of the list items within that element. Keep in mind that the element that is identified by the id=finished could be any element. It doesn't need to be the list tag itself. It could be a div that had a list in it for example.

Selecting by Attribute

Selectors don't only work with elements. You can use them to select by attributes of elements as well. Let's say we wanted to identify all of the items on our todo list that are overdue with the class overdue:

...
<h1>To Do List</h1>
<ol id="todo">
     <li class="overdue">Finish this blog post</li>
     <li class="overdue">Go car shopping with wife</li>
     <li>Cry about 401k</li>
</ol>

<h1>Completed List</h1>
<ol id="finished">
     <li>Dishes</li>
     <li>Laundry</li>
     <li>Email responses</li>
</ol>
...

To iterate over the items that are overdue we could do it two ways. If we want all items that are overdue (regardless of the list), our function could look like this:

function alertItems() {
     $$('li[class="overdue"]').each(function(element) {
          alert(element.innerHTML);
     });
}

However, if we wanted to be specific and only include the items that are overdue in our todo list, we would add the #todo selector so our function looks like this:

function alertItems() {
     $$('#todo li[class="overdue"]').each(function(element) {
          alert(element.innerHTML);
     });
}

Conclusion

CSS selectors are a powerful way to navigate the DOM and are a great tool to have in your belt, wether you are using them for CSS or JavaScript. You can read more about Selectors on the w3c site here: http://www.w3.org/TR/2001/CR-css3-selectors-20011113/#selectors and you can read more about Prototype's $$() function in the Prototype API documentation here: http://www.prototypejs.org/api/utility/dollar-dollar

For reference, the finished HTML document I created for this example is below.

<html>
      <head>
            <script 
     src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js">
     </script>
      </head>
     <body>
          <h1>To Do List</h1>
          <ol id="todo">
               <li class="overdue">Finish this blog post</li>
               <li class="overdue">Go car shopping with wife</li>
               <li>Cry about 401k</li>
          </ol>

          <h1>Completed List</h1>
          <ol id="finished">
               <li>Dishes</li>
               <li>Laundry</li>
               <li>Email responses</li>
          </ol>
          <script>
            function alertItems() {
                 $$('#todo li[class="overdue"]').each(function(element) {
                      alert(element.innerHTML);
                 });
            }
            Event.observe(window, 'load', alertItems);
          </script>
     </body>
</html>

107 Responses

  • paddy responded:

    *sigh* learn to spell "thru" -> "through"

  • Lucas responded:

    Thanks!
    Nice intro to prototype!
    Luc

  • Jeppe responded:

    Thanks! Finally got it to work now!

  • DAVENPORTRobyn responded:

    I had got a dream to start my own business, nevertheless I didn't have enough of money to do this. Thank God my colleague suggested to utilize the home loans. Thence I took the small business loan and made real my desire.

  • personal loans responded:

    Do you understand that it's correct time to get the credit loans, which can make you dreams real.

  • online pokies responded:

    online casino

  • stop snoring responded:

    Thanks for interesting article. I will back here more often and bookmark your site. Please visit and leave comment on my website too :)

  • electronic cigarette responded:

    I like every post in this blog. Really a nice work has done.

  • limewirepros responded:

    I view something truly special in this website.Utterly written articles, Really enjoyed studying.Some truly quality content on this site, saved to fav.

  • Alax responded:

    thanks for sharing this info.If want to find more,you can go to the pages below:
    AB-Selectors Pedals89d8v878vs7
    Simulate Amp Pedals6d87v9ssv
    Effects pedals68dc67d56

  • fat32 to ntfs responded:

    you are in point of fact a good webmaster. The website loading pace is amazing. It kind of feels that you’re doing any distinctive trick. In addition, The contents are masterpiece. you have performed a fantastic process on this matter!

  • app promotion responded:

    hank you for the great information in your article. I feel I will come away a little wiser from the content you’ve written here. I am saving this article to my favorites for further study.

  • bell responded:

    Joyo pedalspamc
    Wah effects Pedalstuvn
    Noise gate Pedalsydbv

  • bell responded:

    Joyo pedalsrinc
    Flanger Pedalsamcv
    Distortion Pedalsrncv

  • bell responded:

    Joyo pedalsiuxyc
    Echo Pedalsojcj
    Modulation Pedalsice

  • bell responded:

    Effects pedalsThe great secret of power is Echo Pedalsnever to will to do more than you can accomplish.Sweeper Pedals

  • Melanie2431 responded:

    Thanks for the good writeup. It in truth was once a enjoyment account it. Glance advanced to far brought agreeable from you! By the way, how can we communicate?
    JOYO JE-306 Tuner
    JOYO JE-309 Tuner
    JOYO JT-20

  • nike sko responded:

    I am sending it to a few friends ans also sharing in delicious. Thanks for making such a killer blog. I arrive on here all the time and am floored with the fresh information here

  • iPhone 4S battery replacement responded:

    very interesting topic , great post.

  • Emergency-tool-kit responded:

    I am really enjoying reading your well written articles. I think you spend numerous effort and time updating your blog.

  • Fake Tag Heuer responded:

    Style displays are constantly happening individuals normally look for ideal duplicate watches.

  • women bandage dress responded:

    Well, very good post with informative information. I really appreciate the fact that you approach these topics from a stand point of knowledge and information. This is the first time, I visited at your site and became your fan. You are bookmarked. Please keep on posting.

  • replica patek philippe sky moon tourbillon responded:

    Yeah bookmaking this wasn't a bad determination great post! .

  • music in real life disney responded:

    This is a wonderful post. I enjoyed the information lot. I will bookmark this page. Thanks for sharing this important information.

  • Wayne responded:

    Another typo: '... is way to large for this tutorial ...' should be '... is way too large for this tutorial ...'

    Nice tutorial though.

  • http://www.storobinlaw.com/medical-malpractice.php responded:

    I just added your site to my favorites. I really enjoy reading your posts. Thanks!

  • is bubblegum casting legitimate responded:

    This blog is fantastic. That's not really a really huge statement, but its all I could come up with after reading this. You know so much about this subject. So much so that you made me want to learn more about it. Your blog is my stepping stone, my friend. Thanks for the heads up on this post.

  • bob forrests new blog post responded:

    Good article i must declare along with cheers to the information. Training is definitely a sticky topic. Nevertheless, remains among Pirate Hay Day the major topics your occasion. When i get pleasure from the article along with count on additional.

  • william gomes responded:

    This was really interesting info in this blog that to very happy for the nice technology in this blog.

  • Pc Repair London responded:

    I am sending it to a few friends ans also sharing in delicious. Thanks for making such a killer blog. I arrive on here all the time and am floored with the fresh information here

  • commonwealth towers at queenstown responded:

    This is a wonderful post. I enjoyed the information lot. I will bookmark this page. Thanks for sharing this information

  • shop reviews responded:

    I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post. Hats off to you! The information that you have provided is very helpful.

  • http://thecommonwealthtower.com.sg responded:

    This is a wonderful post. I enjoyed the information lot. I will bookmark this page. Thanks for sharing this information

  • highlights for light brown hair responded:

    Thank you for presenting your points and providing this information. I have learned something about this topic.

  • http://www.incense-incense.com/ responded:

    This was really interesting info in this blog that to very happy for the nice technology in this blog.

  • democracy protection of minorities responded:

    I just added your site to my favorites. I really enjoy reading your posts. Thanks!

  • musical theater heritage musical monday responded:

    Your articles are always interesting and understandable. Thank you!

  • Meera Funny Interview responded:

    Meera Funny Interview With sohail waraich 2014 for more information meera interview 2014. Pakistani actress Meera Special Interview.

  • meera actress new interview responded:

    Meera Interesting Meeting Using sohail waraich 2014 to learn more meera actress new interview . Pakistani presenter Meera Particular Meeting.

  • High School Diploma Online responded:

    Really well created work you have shared here Thanks for sharing.

  • Mindfulness Courses Dublin responded:

    That is a good idea, I am very happy to read this article, and I agree with the issues of this post. I think this is the best impression. I am going to do something after read.

  • buy valium online responded:

    Great! This is a interesting read. It's a very useful and informative information for me.

  • High School Online responded:

    Good post

  • hana mckin responded:

    Your website is very useful. People will learn a lot from it. You have done a good work. Keep on posting. I appreciate your work.Make Money Online without investment

  • The Forger Official Trailer responded:

    Or opt for 2 DVDs out at one here we are at A year for about $180. Whichever the decision, it's sure to be considered a hit with all the movie fan in your lifestyle.

  • Buy Percocet online responded:

    I was delighted to find this web site.I wanted to thank you for your time reading this wonderful! I really enjoyed every bit of it and I've marked to ensure that the blog post something new.

  • buy hydrocodone online responded:

    I am also interested in this topic. I have spent a lot of time on searching this kind of topic. It is very informative.

  • best iphone 7 case responded:

    i never knew this type of informative posts exist! thnks for sharing it mate!

  • Hostgator Coupon responded:

    Very well done you guys done your work,thanks to inform us about the CSS adn prototype..

  • General category responded:

    Why it is Important for you to know, understand and follow the 10 complete steps to the home buying process in most states.princetonhomes.org

  • mickey mouse games responded:

    Great blog !! please visit my blog to learn more

  • happy wheels responded:

    Hi, Nice post thanks for sharing. Could you please consider adding a link to my website on your page. Please email me back

  • agario responded:

    Hi, very helpful post. Would it be okay for me to provide a guest post on your site? Thanks!

  • Mortal Kombat XL responded:

    In your blog I was happy to see your article, better than last time, and have made great progress, I am very pleased.
    I am looking forward to your article will become better and better.

  • Atari Breakout responded:

    Thanks, you guys that is a great explanation. keep up the good work in your granite blog.

  • Dragon Ball Z Games responded:

    Wonderful blog! This is very informative site. I am totally pleased by your excellent work
    Many thanks for sharing.

  • Godaddy Coupons 2016 responded:

    Eventually the perfect article and a marvelous thinking over your post.Thanks for share this perfect article with us,I just amazed to be here and to read this awesome post.

  • Generic Viagra Wholesale responded:

    Great post with lots of information keep updating with newer post. Nice Work

  • vertix.io responded:

    Thanks for sharing.I hope it will be helpful for too many people that are searching for this topic.

  • Dog Games responded:

    I must appreciate the way you have expressed your feelingsthrough your blog!. Click here to play

  • Fighting Games responded:

    Thank you very much for your post, it makes us have more and more discs in our life, So kind for you,

  • Subway Surfers responded:

    I also hope you will make more and more excellent post and let’s more and more talk, thank you very much, dear.

  • Mickey Mouse Games responded:

    I really hope to see the same high-grade blog posts from you in the future aswell.

  • Russian Escorts in Jaipur responded:

    Thanks for provide this informative article.Thanks for provide this info. Thanks

  • hotmail iniciar sesion responded:

    Hey would you mind letting me know which hosting company you're utilizing? I've loaded your blog in 3 completely different browsers and I must say this blog loads a lot faster then most. Can you recommend a good hosting provider at a reasonable price? Thank you, I appreciate it!

  • Obat Batu Ginjal responded:

    Your website is very interesting, it is very meaningful and inspirational. I think your website deserves to be the number one. hopefully it could be real. Thank you in advance for own variety. I wish all of you is given a long life in order to continue working

  • dish coupons responded:

    Your article have simply amazing in all the points and target the online peoples. Keep sharing here!

  • Obat Ambeien responded:

    Your website is very interesting, it is very meaningful and inspirational. I think your website deserves to be the number one. hopefully it could be real. Thank you in advance for own variety. I wish all of you is given a long life in order to continue working

  • Obat Penghancur Lemak responded:

    I am very happy to be visited here, it was nice nice. may be a website no one

  • Obat Tradisional Epilepsi responded:

    epilepsy is a disease caused due to disturbances in neurons (nerve cells) in the brain. Nerve cells are part of the nervous system that functions as a regulator of awareness, the ability to think, gestures, and the system of our senses.

  • Obat Darah Tinggi responded:

    If you already know the symptoms of high blood pressure in pregnant women, immediately do the treatment as soon as possible, because this disease is very dangerous

  • Obat Amandel responded:

    Website that you create really really nice and very interesting to see in. I am very happy to be visiting here http://www.obatasamuratalami.net/

  • Obat Sinusitis responded:

    I read your complete survey. It's really great & amazing presentation. Thanks a lot for providing this marvelous information which i need so much http://www.ahlinyapengobatanhe...ara-alami/

  • hostgator black friday 2016 deals responded:

    I have visited your website.It is very interesting and impressive.Thanks for sharing with us such a brilliant article.I want to come again.Keep updated.

  • Obat Polip Hidung responded:

    I am very happy to be one of the visitors on your website. The article was so cool. If you have health problems visit us at

  • cara menyembuhkan darah tinggi responded:

    thanks for providing information that is very useful to us, the beauty of sharing may be useful for you all :)

  • Cara mengatasi radang telinga responded:

    Thank u so much admin and sorry permission share in here :)

  • cara menyembuhkan gabagen responded:

    Thank u so much admin and sorry permission share in here :)

  • cara mengatasi mata buram responded:

    http://www.gamatasli.com/keseh...-diabetes/

  • ginkgo biloba plus capsule responded:

    http://www.gamatasli.com/obat-...s-capsule/

  • zinc tablet green world responded:

    http://www.gamatasli.com/obat-...een-world/

  • jian xin capsule responded:

    http://www.gamatasli.com/obat-...n-capsule/

  • triflex capsule responded:

    http://www.gamatasli.com/obat-...x-capsule/

  • cara membersihkan rahim setelah keguguran responded:

    http://www.gamatasli.com/keseh...keguguran/

  • ovary nutrition capsule responded:

    http://www.gamatasli.com/obat-...n-capsule/

  • jual rumah di pontianak responded:

    In your blog I was happy to see your article, better than last time, and have made great progress, I am very pleased.
    I am looking forward to your article will become better and better.

  • cara menyembuhkan polip hidung responded:

    article was very nice and helpful at all for me thank you very much and sorry admin me permission to share articles herein may be useful and helpful

  • Cara menyembuhkan flu tulang responded:

    Thank you so much admin is already providing the information to us and here we are sorry permission to share articles may be useful and helpful

  • Obat Ginjal Bengkak responded:

    I don’t have the time at the moment to fully read your site but I have bookmarked it and also add your RSS feeds. I will be back in a day or two. thanks for a great site.

  • Obat Sakit Pinggang responded:

    Your website is very interesting, it is not boring and full of inspiration that you devote. Thanks to all the articles that you serve. I must recommend your website to friends. Good Luck

  • cara menyembuhkan ginjal mengecil responded:

    thank u very much admin and sorry permission share in here

  • Ajmer Call Girls responded:

    Great post here is more information for us thanks for sharing with us.

  • Obat maag akut alami responded:

    thank u so much admin and sorry permission share in here :)

  • cerita humor lucu responded:

    thanks for sharing

    i think this css very importhan for blog

  • Obat Gangguan Pencernaan untuk Anak responded:

    The article is very interesting to see, thank you for sharing this very interesting information

  • Pengobatan Tradisional Rematik responded:

    Thanks for sharing information very interesting and useful. Do not forget to visit our website to share information and knowledge about health

  • Obat Patah Tulang Paha responded:

    Previously we ask for permission to share, perhaps from you no trouble finding herbal medicinal agent QNC Jelly Gamat. This is the official agent QNC Jelly Gamat are ready to serve the order and delivery. thank you

  • Obat Radang Sendi Lutut Paling Ampuh responded:

    Thanks for sharing the information...Success for the website, as well as the previously asked permission to visit here ...

  • Obat Penyakit Kencing Manis responded:

    The information is very useful and interesting. Thanks for sharing and do not forget to visit our website to share information and knowledge

  • obat darah tinggi responded:

    a given article is very interesting and very useful for me, thank you very much admin and pardon me permission to share the article here

  • pengobatan untuk sembuhkan maag kronispengobatan untuk sembuhkan maag kronis responded:

    I still liked this article, good, good content, and unique design.Thank you for sharing the article.

  • HP Customer Service responded:


    I truly cherish perusing and taking after your post as I discover them to a great degree useful and intriguing. This post is similarly educational and also fascinating . Much obliged to you for data you been putting on making your site such an intriguing.

  • Norton Customer Service responded:

    Wow,Great post,Keep it up,I wants you to look my site link If there are some issue then tell me,Thanks

  • Driver Toolkit License Key responded:

    Great info. Lucky me I found your site by accident (stumbleupon).I have bookmarked it for later!

  • HP support responded:

    very useful content. great work.. thanks .. for more information you should go to the link given

  • Buy Vicodin Safe Online responded:

    Thanks for sharing about this CSS problem. Its Helps alot in CSS selector. Must appreciate your work.

  • Cara menyembuhkan asam urat responded:

    Thank u so much admin and sorry permission share in here :)

Add your own comment...


busy