Using CSS Selectors in JavaScript - getElementsBySelector()

getElementsBySelector() function returns the DOM elements based on the CSS selectors provided by the user. Supports CSS3 Selectors.

This function is the remake of the getElementsBySelector() function by Simon Willison. His function did not support the ',' selector - so I decided to make my own version.

Code

css_selector.js - V 1.00.A Beta
3.4 KB Uncompressed
90 Lines

Unsupported selectors

Demo



Sample Text...

Taken from Wikipedia. Use the above form to select the elements here with CSS selectors. The selected elements will have a red border. View the source to see the HTML behind this.

In CSS, selectors are used to declare which elements a style applies to, a kind of match expression. Here are some examples of selector syntax:

All elements
that is, using the * selector
By element name
e.g. for all p or h2 elements
Descendants
e.g. for a elements that are descendants of li elements (e.g links inside lists) the selector is li a
class or id attributes
e.g. .class and/or #id for elements with class="class" or id="id"
Adjacent elements
e.g. for all p elements preceded by h2 elements, the selector would be h2 + p
Direct child element
e.g. for all span elements inside p, but no span elements deeper within the hierarchy, the selector would be p > span
By attribute
e.g. for all <input type="text"> the selector would be input[type="text"]

In addition to these, a set of pseudo-classes can be used to define further behavior. Probably the best-known of these is :hover, which applies a style only when the user 'points to' the visible element, usually by holding the mouse cursor over it. It is appended to a selector as in a:hover or #elementid:hover. Other pseudo-classes and pseudo-elements are, for example, :first-line, :visited or :before. A special pseudo-class is :lang(c), where the style would be applied on an element only if it is in language "c".

Selectors may be combined in other ways too, especially in CSS 2.1, to achieve greater specificity and flexibility (see the complete definition of selectors at the W3C Web site).

In the following example, several selectors are grouped using comma separation[2]. The rule sets the font for all HTML headings.

h1, h2, h3, h4, h5, h6 {
    font-family: "Arial", sans-serif;
}

Similar Functions

blog comments powered by Disqus