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
- < Child selector
- + Sibling selector
- : pseudo-class
- :: pseudo-elements
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
orh2
elements - Descendants
- e.g. for
a
elements that are descendants ofli
elements (e.g links inside lists) the selector isli a
- class or id attributes
- e.g.
.class
and/or#id
for elements withclass="class"
orid="id"
- Adjacent elements
- e.g. for all
p
elements preceded byh2
elements, the selector would beh2 + p
- Direct child element
- e.g. for all
span
elements insidep
, but nospan
elements deeper within the hierarchy, the selector would bep > span
- By attribute
- e.g. for all
<input type="text">
the selector would beinput[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
- InterModule - a new library that uses this script
- Original getElementsBySelector() by Simon Willison
- Select with style
- cssQuery
- Behaviour