---
created_at: '2009-08-22T19:24:02.000Z'
title: The Notes What Spawned JQuery (2005)
url: http://ejohn.org/blog/selectors-in-javascript/
author: fogus
points: 48
story_text: ''
comment_text: 
num_comments: 7
story_id: 
story_title: 
story_url: 
parent_id: 
created_at_i: 1250969042
_tags:
- story
- author_fogus
- story_779690
objectID: '779690'

---
[Source](https://johnresig.com/blog/selectors-in-javascript/ "Permalink to John Resig -   Selectors in Javascript")

# John Resig -   Selectors in Javascript

* [Home][1]
* [Blog][2]
* [Projects][3]
* [Speaking][4]
* [Research][5]
* [About][6]

![John Resig][7]][6]

John Resig  

* [Subscribe][8]
* [Contact][6]

## Selectors in Javascript

Ever since the [Behaviour][9] code was released, some time ago, my mind has been churning this powerful topic over. The premise for the module is as follows: Using the power of [Pseudo-CSS Selectors][10], bind your Javascript functions to various HTML elements in the DOM. Looking at how Behaviour works, I’ve never been completely happy – it simply seems too tedious and verbose for everyday use. I’ve since begun to tinker with different styles of code layout – trying to find an optimal solution. Some of my biggest gripes with Behaviour are:

* You can’t do any heirarchical selectors. For example, binding to “#foo bar” and “#foo bar .baz” fall under two completely different statements. It seems as if this could/should be streamlined.
* The Behaviour object doesn’t provide any sort of binding-enhancers to make attaching to an event (e.g. “click”) easier to do.
* The resulting Behaviour code is simply too verbose and too ugly – there is an excess of characters/formatting which will probably scare off a casual Javascript programmer.

I’ve created a syntactical mock-up for how _I think_ ‘Behaviour’ could’ve been implemented. I’m not sure if I’m completely happy with it yet – the only way to know is to do some real-world testing and come back with some tweaks.

## Sample #1

Note: In all of these examples, Behaviour uses ‘element.onclick’ (or similar bindings) in order to attach an event handler – this is generally accepted as an improper way of doing this, since you will only be able to attach one event handler at a time – newer handlers will overwrite older ones.
    
    
      Behaviour.register({
        '#example li': function(e){
          e.onclick = function(){
            this.parentNode.removeChild(this);
          }
        }
      });

The same as above, done in my code:
    
    
      $('#example li').bind('click',function(){
        this.parentNode.removeChild(this);
      });

**Syntactic fluff comparision** (This is a comparision of how many extra non-critical characters there are, slowing the programmer down – not counting endlines/whitespace):
    
    
    A: Behaviour.register({'':function(e){e.on=}});
    B: $('').bind('',);

## Sample #2

This is the second example made available on the Behaviour web site. It goes to two disparate branches in the DOM Document and attaches two different event handlers.
    
    
      Behaviour.register({
        'b.someclass' : function(e){
          e.onclick = function(){
            alert(this.innerHTML);
          }
        },
        '#someid u' : function(e){
          e.onmouseover = function(){
            this.innerHTML = "BLAH!";
          }
        }
      });

The same as above, done using my syntax:
    
    
      $('b.someclass').bind('click',function(){
        alert(this.innerHTML);
      });
    
      $('#someid u').bind('mouseover',function(){
        this.innerHTML = 'BLAH!';
      });

**Syntactic fluff comparision**
    
    
    A: Behaviour.register({'':function(e){e.on=},'':function(e){e.on=}});
    B: $('').bind('',);$('').bind('',);

## Sample #3

This is the Behaviour code required to meet a ‘more advanced’ test case. I included changing style properties and element attributes.
    
    
      Behaviour.register({
        '#foo ol li': function(a) {
          a.title = "List Items!";
          a.onclick = function(){alert('Hello!');};
        },
        '#foo ol li.tmp': function(a) {
          a.style.color = 'white';
        },
        '#foo ol li.tmp .foo': function(a) {
          a.style.background = 'red';
        }
      });

And the same result using my syntax:
    
    
      $('#foo ol li')
        .set('title','List Items!')
        .bind('click',function(){alert('Hello!');})
        .select('.tmp')
          .style('color','white')
          .select('.foo')
            .style('background','red');

**Syntactic fluff comparision** For this comparision I included the selectors that Behaviour uses, but shouldn’t need to.
    
    
    A: Behaviour.register({'':function(a){a.=;a.on=;},'#foo ol li':function(a){a.style.='';},'#foo ol li.tmp':function(a){a.style.='';}});
    B: $('').set('','').bind('',).select('').style('','').select('').style('','');

I’m going to have some more information on, how exactly, this new method of binding would work – hopefully along with some demoable code. More coming very soon!

**Posted:** August 22nd, 2005 
* * *

[**Subscribe for email updates][8]**

####  3 Comments [(Show Comments)][11]

1. ### [**Emmett Shear][12]** (August 22, 2005 at [9:12 am][13]) 

I’ve been looking at Behavior as well for my AJAX site (going beta in a week or so!), but was turned off for the same reason you were. I have some code which is in effect doing what you’re talking about here, but it’s not so neatly bound with the dom objects. I’ll be sure to check back, and I’d be glad to help you try and test it if you get something running.

2. ### [**Bob Aman][14]** (August 22, 2005 at [10:54 am][15]) 

Great stuff John. Thanks for doing this. I was using Behavior too, and yeah… wasn’t a fan of those things either, especially since I’m trying to serve up application/xhtml+xml and I ran into lots of problems with Behavior in that setting. So I stopped working with Behavior and went back to the old way of doing things because I was too lazy to fix it.

3. ### [**Ben Darlow][16]** (October 5, 2005 at [5:42 am][17]) 

Very good points. I myself only recently discovered and played with Behaviours, but was disappointed by the limited support for CSS selectors (in particular, attribute selectors). A better implementation would be very welcome!

  

* * *

**Comments are closed.**  
Comments are automatically turned off two weeks after the original post. If you have a question concerning the content of this post, please feel free to [contact me][6].

* * *

![Secrets of the JavaScript Ninja][18]

### [Secrets of the JS Ninja][19]

Secret techniques of top JavaScript programmers. Published by Manning.

### [Subscribe for email updates][8]

![John Resig Twitter Updates][20]

### [@jeresig][21]

Infrequent, short, updates and links.

[1]: https://johnresig.com/
[2]: https://johnresig.com/category/blog/
[3]: https://johnresig.com/projects/
[4]: https://johnresig.com/speaking/
[5]: https://johnresig.com/research/
[6]: https://johnresig.com/about/
[7]: https://johnresig.com/wp-content/uploads/2017/04/cropped-cropped-jeresig-2016.1024.jpg
[8]: https://johnresig.com/subscribe/
[9]: http://bennolan.com/behaviour/
[10]: http://www.w3.org/TR/REC-CSS2/selector.html
[11]: https://johnresig.com#postcomment "Jump to the comments form"
[12]: http://www.kiko.com
[13]: https://johnresig.com#comment-608 "Permanent link to this comment"
[14]: http://sporkmonger.com/
[15]: https://johnresig.com#comment-609 "Permanent link to this comment"
[16]: http://www.kapowaz.net
[17]: https://johnresig.com#comment-919 "Permanent link to this comment"
[18]: https://johnresig.com/files/jsninja.74.jpg
[19]: https://amzn.to/2oiS4em
[20]: https://johnresig.com/images/twitter-74.png
[21]: https://twitter.com/jeresig

