Wednesday, January 18th, 2006

Prototype adds CSS selector function: $$(‘div#page p.summary img’)

Category: Library, Prototype, Tip

<p>Those prototype folks love their magic functions don’t they :)

This time, Sam Stephenson has added some CSS selector magic to the Prototype trunk.

Example: Find all elements inside

elements with class “summary�, all inside the

with id “page� and hide each matched tag:

javascript
< view plain text >
  1. $$('div#page p.summary img').each(Element.hide);

For fun, look at the function itself (obviously using all of the other nice prototype functions):

javascript
< view plain text >
  1. function $$() {
  2.   return $A(arguments).map(function(expression) {
  3.     return expression.strip().split(/\s+/).inject([null], function(results, expr) {
  4.       var selector = new Selector(expr);
  5.       return results.map(selector.findElements.bind(selector)).flatten();
  6.     });
  7.    }).flatten();
  8. }

( via Thomas Fuchs )

Related Content:

Posted by Dion Almaer at 12:28 pm
28 Comments

++++-
4 rating from 94 votes

28 Comments »

Comments feed TrackBack URI

Nice! I have to change it to something else but $$ because my stupid template class things it’s a variable :(

Comment by Dominik Hahn — January 18, 2006

I’ve been using behaviors.js to do this kind of javascript by css-selector for a while, it’s awesome. You can find it at http://bennolan.com/behaviour/

Comment by Mike Ritchie — January 18, 2006

That code is extremely suspect (although, probably just a matter of coincidence) – jQuery, which was just announced this weekend at BarCampNYC, is visually very similar. However, the code produced by jQuery is much much more powerful. I highly recommend that you check it out.

Comment by John Resig — January 18, 2006

Nice feature. Any benchmarks?

I would be surprised if it was anywhere near something that one could call “reasonable fast” with all the rather slow Enumerable abstraction going on.

Mind you, Enumerable is very elegant, but slow nonetheless.

Comment by Mike — January 18, 2006

I never get this kind of stuff… It looks cool, but what do you use it for?

Wouldn’t it be far more useful and understandable and faster and extensible and saner and less buggy to do the following instead:

CSS:
.hideimgs img { display:none; }

JS:
document.getElementById(“page”).className += ” hideimgs”;

Bingo! Same result.
My point: when and why do you need to select element using a CSS selector? If it’s for styling/hiding them use CSS. Someone has another reason? Please tell me.

Comment by Lon — January 18, 2006

Lon, it’s useful if you need to do JavaScript stuff with the resulting objects. Say, for sIFR it’s the way to select the elements you want to replace.

Comment by Mark Wubben — January 18, 2006

As another explanation, CSS selectors are an alternative to XPath (neither of which have convenient, built-in programmatic support across all major browsers, especially when it comes to HTML pages). Sometimes IDs are good enough, but not always.
Looking at the source, what’s nice here is that they compile the selectors to JavaScript, which means it runs at full JS speed. Maybe not fast, but should be much faster than an interpreter running inside JS (as Behaviour seems to do).
Benchmarks would be very interesting.

Comment by Tom — January 18, 2006

[...] From Ajaxian: Example: Find all elements inside elements with class “summaryâ€?, all inside the with id “pageâ€? and hide each matched tag: $$(‘div#page p.summary img’).each(Element.hide); [...]

Pingback by Labnotes » Blog Archive » Prototype adds CSS selectors — January 18, 2006

Er, John, you’re getting a little overzealous there… nobody’s copying anyone else, we’re all just standing on each other’s shoulders.

Comment by Bob Aman — January 19, 2006

@Bob Aman: Don’t feed the trolls. :)

Comment by Thomas Fuchs — January 20, 2006

Lon,

My point: when and why do you need to select element using a CSS selector? If it’s for styling/hiding them use CSS.

Often times you don’t want to set things to display:none in your CSS directly. If the device reading the page does not support javascript, the element that has no display will never be able to be seen. So, for example, you set all of the things you want hidden to display:none at window.onload, and users or agents that don’t parse javascript can still access the content.

Comment by Mike P. — January 20, 2006

Mike P.,
you can achieve what you are descibing much easier:
document.write(“”);
Put all CSS that is only allowed if script is present in scriptonly.css.
Or, maybe better, the other way around:

Comment by Lon — January 21, 2006

Let’s try that again:
Mike P.,
you can achieve what you are describing much easier:
document.write(â€?”);
Put all CSS that is only allowed if script is present in scriptonly.css.
Or, maybe better, the other way around:

Comment by Lon — January 21, 2006

you would want this in case you have some divs that you need to change on the fly, but you don’t know what the ‘id’s are because they are dynamically created. you just know where they are by their class name.

i hope! because otheriwse this isn’t going to work out too well for me!

Comment by jason — March 6, 2006

[...] That’s good – but say you want to round and fade many elements on a page – and you don’t want to repeat the same code over and over. Another new addition to Prototype Selector magic comes to the rescue – here we are applying the round and fades to all divs with the roundAndFade class: $$(‘div.roundAndFade).each(Element.Round(’roundMeClass’).FadeTo(0.2, 500, 10)); [...]

Pingback by Rico Words » Prototyping the future — March 11, 2006

[...] While working on the future AJAX interface of jamendo, I ran into some performance problems that were due to the extensive use of the new Prototype 1.5 function, $$. (Announcement of $$ on Ajaxian) [...]

Pingback by Sylvain Zimmer » Speeding up Prototype’s Selector — June 25, 2006

[...] We hebben het de afgelopen tijd gehad over verschillende javascript libraries die CSS-style selectors aankonden, zoals jQuery en Behaviour. Maar ook de opkomende versie van Prototype: prototype 1.5.0, zal ook in staat zijn om DOM elementen te selecteren met CSS-style selectors. Hiervoor gebruik je dan de $$() functie: PLAIN TEXT JAVASCRIPT: [...]

Pingback by Prototype en CSS-style selectors | Scriptorama — July 21, 2006

미국에서 이미 성공한 사업입니다.
국내에는 아는 분 거의 없습니다.
도메인 관련 사업입니다.
읽어보시면 아~ 이래서 돈을 버는구나 하실 겁니다.
정보도 정보나름입니다.
영어번역의 문제를 해결하였습니다.
완벽한 마케팅 도구를 제공합니다.
투자비용요? 월 1만원입니다.
궁금한 분은 maestrointernation@hotmail.com 로 메일주세요.
자료를 메일로 보내드리겠습니다.
제가 지금껏 접한 정보 중 단연 최고라고 자신있게 말씀드립니다.

운영자님! 게시물이 맞지 않으면 삭제바랍니다.
게시판의 url을 알려주시면 다시는 올리지 않겠습니다.
사업 번창하세요. 삭제는 1111입니다.

Comment by 도메인 — August 18, 2006

[...] Prototype adds CSS selector function: $$ October 15th, 2006 | Category: CSS selector [...]

Pingback by Prototype.js Documentation » Prototype adds CSS selector function: $$ — October 17, 2006

i have no idea what that means?
strange
oh well
have a good christmas

Comment by sun bingo — December 12, 2006

keep it up and thanks for the info
ive learnt a lot

have a good new year

Comment by new vauxhall corsa — December 26, 2006

good luck in 2007

Comment by tgi fridays — January 1, 2007

this is pretty fast considering the Enumerable abstraction is going on

Comment by fast uk secured loan — January 5, 2007

We hebben het de afgelopen tijd gehad over verschillende javascript libraries die CSS-style selectors aankonden, zoals jQuery en Behaviour

Comment by free affiliate program — January 6, 2007

I need to find a way to have Scriptaculus blind to work with sIFR!… Because the div’s are styled inline with display:none it won’t render the flash when the div blinds or slides or fades and any of the effects actually :)

Anyone got and cleaver ideas?

Comment by Search Engine Optimisation — August 16, 2007

thanks for a great article

Comment by bingo scotland — October 8, 2007

Nice! I have to change it to something else but $$ because my stupid template class things it’s a variable

Comment by free ps3 — November 9, 2007

css web template page (example) — http://www.css-lessons.ucoz.com/css-template-page.htm

Comment by yildizx — May 13, 2008

Leave a comment

You must be logged in to post a comment.