Matching Element Against CSS Selector

From RuntimeWiki

Jump to: navigation, search

Contents

Title

API Support for Matching an Element against a CSS Selector

Detailed write-up

Description

The new generation of browsers is implementing querySelector APIs to query the DOM for a CSS selector. The reverse operation, checking that a given element matches a selector, is not available.

Why Is This Important?

Thanks to event bubbling, it is possible to set-up event sinks that catch most events at the window level. This has the nice advantage that elements can be destroyed without having to clean-up events and elements can be created (with events already working), even using innerHTML, without the need to wire-up events. Such a system needs to route the different events to the right handlers, and CSS selectors are a nice way to specify those routing rules.

Possible solutions

The feature can be implemented this way (provided querySelectorAll is available):

function(selector, element) {
   var allMatches = document.querySelectorAll(selector);
   for (var i = 0; i < allMatches.length; i++) {
       if (allMatches[i] === element)
           return true;
   }
   return false;
}

or by applying a JavaScript implementation of CSS selectors to the element. Both approaches are highly inefficient. Notice how even the implementation that leverages the native querySelectorAll still requires looping over a potentially large set of nodes.

Background material that request this feature

Discussion

Phase I Voting - Vote for Your Top 5 Features

NOTE: PHASE I VOTING IS NOW OPEN. (2008-04-01) We have now changed the voting procedure. Instead of putting votes on each separate wiki page, we are asking people to cast their Phase I Votes on the following wiki page:


Phase II Voting

More about this later.

Personal tools