Jihad Haddad
Jihad Haddad

Reputation: 642

Detecting specific HTML elements to add onclick event on them

I want to add an onclick event on a number of HTML elements on my page dynamically. What is the best way to search and find those elements, not having their ids in hand and knowing that the HTML elements do not have anything in common.

A way of doing this is to add a CSS class ('add-onclick') to all the elements and iterate through document and for each HTML tag 'elem' perform the following check:(elem.className.indexOf('add-onclick') != -1)

The only downside I can see to this, is that I am using a CSS class for something other than styling. Is this totally illegal, and what other options do I have?

I am using XHTML 1.0 Transitional, and no HTML5 is not an option.

Thanks a lot Jihad

Upvotes: 0

Views: 315

Answers (3)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201758

The best way depends on the context and criteria.

There is nothing wrong with using classes for the purpose. Classes are a markup language concept, and there are no “CSS classes” – just use of class selectors in CSS – and there is no requirement that classes be used only for styling.

Traversing a document tree and checking the classes of each element is possible of course. However, this might be something that jQuery is appropriate for. Using jQuerym you would need just the statement $('.add-onclick').click(handleClick) if all the elements in the class should have the same event handler function handleClick.

Upvotes: 0

QuarK
QuarK

Reputation: 2536

You can put a prefix to the classes, I mean click_redbg or click_bluebg and use regular expressions with jQuery or Prototype:

$("div[class^='click_']").each(function(e) { ... });

Upvotes: 1

Vengarioth
Vengarioth

Reputation: 684

Well there are many Javascript Frameworks out there featuring "delegations", most dont require html5 features (since its normal ECMA script).

delegations are basicly catching DOM-events at a higher level then the event was thrown at (DOM events bubble down the dom till they hit the most bottom element, then up again and notify every event handler on the elements they passed in the route)

if you want to implement those without using a framework, you can add a click event to the document body (for example). This event gets all clicks on your page, since the "most bottom element" is stored in the event's data, you can set up css rules for that element and delegate on to your implementation of delegations.

Upvotes: 0

Related Questions