views:

568

answers:

6

Hi,

I need to add a onClick event to a around 10-20 elements on a page.

What would be the fastest way to reference those elements?

Would it be using: 1) class reference 2) ID reference

Or a more drilled down reference like: p -> div -> li ?

I realize we are probably talking a very small performance gain, but I think its good to know either way.

A: 

How were you planning on selecting 10-20 different elements using an ID?

Class reference would be the way to go I'd say.

Steerpike
While certainly NOT recommended, 10 - 20 IDs could be selected as such: $("#id1,#id2,#id3,etc...") // multiple selectorsOR $("[id^='id']") //attribute begins with
Richard B
A: 

If you surround the content with a div and does the (div -> li). Then you wouldn't have to write alot of tags on each element, but definitely class over id

Frost
+4  A: 

That's really not enough elements to worry about. Unless you have a lot of things going on in your page, I would say use jQuery and a class selector, for maintainability and redability, and move on to tougher code. :)

If you are concerned, test it yourself by loosely benching it in your script.

Added: To directly answer your question of selector speed: #id >> tag.class > .class. Please note that over 20000 elements, the benched time differs at most by ~700ms between the id-based search and the pure class-based search. That's why I suggest you don't worry too much... :)

alphadogg
A: 

Depends on the situation. 10-20 elements that are nicely segregated either by type or hierarchy so you can refer to just those elements and not any others. I'd use either a hierarchical or attribute-based selector. 10-20 elements that are interspersed with other elements of the same type to which the selector should not apply, then I'd assign and use a class. The latter is probably the most flexible if you think that the layout may change and break the other selectors.

$('div#interface > a').click( ... )

$('input[type=button]').click( ... )

$('span.clickable').click( ... )
tvanfosson
A: 

You will have to find a pattern in your elements and the also the others elements on your page.

Do they have the same class? Are there other elements on the page you don't want to select, but do have the same class? Same story for selection based on the html-tags.

And you have to make a decission based on the output of your "analysis" of the elements.

Natrium
A: 

Since yre adding onClick events, look into event delegation. It's changed my life. :-)

Basically you would assign a listener to a container, and catch the click events on these 20 items. Not sure if it's relevant to what yre trying to do, but I think it's great for everyone to know about.

Corey Maass