diff --git a/.eslintrc.yml b/.eslintrc.yml deleted file mode 100644 index 570fefd..0000000 --- a/.eslintrc.yml +++ /dev/null @@ -1,123 +0,0 @@ -env: - amd: true - browser: true - commonjs: true - -rules: - accessor-pairs: 2 - array-callback-return: 2 - block-scoped-var: 0 - class-methods-use-this: 2 - complexity: 0 - consistent-return: 2 - curly: 0 - default-case: 2 - dot-location: 2 - dot-notation: 0 - eqeqeq: 2 - for-direction: 2 - getter-return: 2 - guard-for-in: 0 - init-declarations: 0 - no-alert: 2 - no-await-in-loop: 2 - no-caller: 2 - no-case-declarations: 2 - no-catch-shadow: 2 - no-compare-neg-zero: 2 - no-cond-assign: 2 - no-console: 0 - no-constant-condition: 2 - no-control-regex: 0 - no-debugger: 2 - no-delete-var: 2 - no-div-regex: 2 - no-dupe-args: 2 - no-dupe-keys: 2 - no-duplicate-case: 2 - no-else-return: 2 - no-empty-character-class: 2 - no-empty-function: 2 - no-empty-pattern: 2 - no-empty: 2 - no-eq-null: 2 - no-eval: 2 - no-ex-assign: 2 - no-extend-native: 2 - no-extra-bind: 2 - no-extra-boolean-cast: 2 - no-extra-label: 2 - no-extra-parens: 2 - no-extra-semi: 2 - no-fallthrough: 2 - no-floating-decimal: 2 - no-func-assign: 2 - no-global-assign: 2 - no-implicit-coercion: 2 - no-implicit-globals: 2 - no-implied-eval: 2 - no-inner-declarations: 2 - no-invalid-regexp: 2 - no-invalid-this: 2 - no-irregular-whitespace: 2 - no-iterator: 2 - no-label-var: 2 - no-labels: 2 - no-lone-blocks: 2 - no-loop-func: 2 - no-magic-numbers: 0 - no-multi-spaces: 2 - no-multi-str: 2 - no-new-func: 0 - no-new-wrappers: 2 - no-new: 2 - no-obj-calls: 2 - no-octal-escape: 2 - no-octal: 2 - no-param-reassign: 0 - no-proto: 0 - no-prototype-builtins: 2 - no-redeclare: 2 - no-regex-spaces: 2 - no-restricted-globals: 2 - no-restricted-properties: 2 - no-return-assign: 2 - no-return-await: 2 - no-script-url: 2 - no-self-assign: 2 - no-self-compare: 2 - no-sequences: 2 - no-shadow-restricted-names: 2 - no-shadow: 0 - no-sparse-arrays: 2 - no-template-curly-in-string: 2 - no-throw-literal: 2 - no-undef-init: 2 - no-undef: 2 - no-undefined: 0 - no-unexpected-multiline: 2 - no-unmodified-loop-condition: 2 - no-unreachable: 2 - no-unsafe-finally: 2 - no-unsafe-negation: 2 - no-unused-expressions: 0 - no-unused-labels: 2 - no-unused-vars: 2 - no-use-before-define: 0 - no-useless-call: 2 - no-useless-concat: 2 - no-useless-escape: 2 - no-useless-return: 2 - no-void: 2 - no-warning-comments: 2 - no-with: 2 - prefer-promise-reject-errors: 2 - radix: 2 - require-await: 2 - strict: 0 - use-isnan: 2 - valid-jsdoc: 2 - valid-typeof: 2 - vars-on-top: 0 - wrap-iife: 0 - yoda: 2 diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml deleted file mode 100644 index 0873017..0000000 --- a/.github/workflows/node.js.yml +++ /dev/null @@ -1,28 +0,0 @@ -name: nwsapi - -on: - push: - branches: - - main - pull_request: - branches: - - main - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - name: Checkout repository - uses: actions/checkout@v2 - - - name: Setup Node.js - uses: actions/setup-node@v2 - with: - node-version: '14' - - - name: Install dependencies - run: npm install - - - name: Run tests - run: npm testIs the NodeJS yaml configuration needed in my "nwsapi" repository ? diff --git a/.gitignore b/.gitignore index 5be2eea..585a5f4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules/ package-lock.json -yarn.lock +test-results/ +.last-run.json diff --git a/Makefile b/Makefile deleted file mode 100755 index 84068ab..0000000 --- a/Makefile +++ /dev/null @@ -1,58 +0,0 @@ -# -# Makefile -# -# NWSAPI distribution builder -# -# currently just a wrapper for: -# -# - nwjslint.sh (writes to lint.log) -# - nwpackjs.sh (writes to dist.log) -# -# minifier by Dean Edwards -# - -# getting path -SOURCES=./ - -# resets default rules -.SUFFIXES: - -# just in case they exists -.PHONY: all clean dist lint - -# add a SILENT flag to stop -# showing directories access -ifeq ($(filter -s,$(MAKEFLAGS)),) -MAKEFLAGS += -s -endif - -# shell scripts directory -SCRIPTS=${SOURCES}/build/scripts - -# default all stages -all: - @make clean ${SOURCES} - @make lint ${SOURCES} - @make dist ${SOURCES} - @make test ${SOURCES} - -# clean stage -clean: - @rm -f dist/nwsapi.js - @rm -f dist/nwsapi-min.js - @rm -f dist/nwsapi-pac.js - @rm -f dist/nwsapi-src.js - @rm -f dist/nwsapi-zip.js - @rm -f dist/lint.log - -# dist stage -dist: - @${SCRIPTS}/nwpackjs.sh ${SOURCES} - -# lint stage -lint: - @${SCRIPTS}/nwjslint.sh ${SOURCES} - -# test stage -#test: -# @${SCRIPTS}/nwtestjs.sh ${SOURCES} diff --git a/bin/jsl.exe b/bin/jsl.exe deleted file mode 100755 index 30dbd14..0000000 Binary files a/bin/jsl.exe and /dev/null differ diff --git a/bin/jsl_linux b/bin/jsl_linux deleted file mode 100755 index b2882eb..0000000 Binary files a/bin/jsl_linux and /dev/null differ diff --git a/bin/jsl_macos b/bin/jsl_macos deleted file mode 100755 index bb6db74..0000000 Binary files a/bin/jsl_macos and /dev/null differ diff --git a/bin/jsmin.exe b/bin/jsmin.exe deleted file mode 100755 index 17f9a89..0000000 Binary files a/bin/jsmin.exe and /dev/null differ diff --git a/bin/jsmin_linux b/bin/jsmin_linux deleted file mode 100755 index 8117c98..0000000 Binary files a/bin/jsmin_linux and /dev/null differ diff --git a/bin/jsmin_macos b/bin/jsmin_macos deleted file mode 100755 index a96e1d6..0000000 Binary files a/bin/jsmin_macos and /dev/null differ diff --git a/bin/os_list b/bin/os_list index c30d331..fd41d7a 100644 --- a/bin/os_list +++ b/bin/os_list @@ -1,21 +1,15 @@ Linux ================================ js_linux - Spidermonkey 1.8.0 -jsl_linux - Javascript Lint -jsmin_linux - JS Minifier MacOSX ================================ js_macos - Spidermonkey 1.8.0 -jsl_macos - Javascript Lint -jsmin_macos - JS Minifier Windows ================================ js.exe - Spidermonkey 1.8.0 -jsl.exe - Javascript Lint -jsmin.exe - JS Minifier cygwin1.dll - DLL diff --git a/bower.json b/bower.json deleted file mode 100644 index 202686a..0000000 --- a/bower.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "nwsapi", - "version": "2.2.23", - "homepage": "https://github.com/dperini/nwsapi", - "authors": [ - "Diego Perini " - ], - "description": "Fast CSS Selectors API Engine", - "main": "src/nwsapi.js", - "moduleType": [ - "globals" - ], - "keywords": [ - "javascript", - "selector", - "matcher", - "library", - "nwsapi" - ], - "license": "MIT", - "ignore": [ - "*/.*", - "*.md", - "bin", - "test", - "dist", - "build", - "Makefile", - ".gitignore", - ".npmignore", - "package.json", - ".gitattributes" - ] -} diff --git a/build/HEADER b/build/HEADER deleted file mode 100644 index 43cf79a..0000000 --- a/build/HEADER +++ /dev/null @@ -1,5 +0,0 @@ -/*! - * NWSAPI 2.2.23 - Fast CSS Selectors API Engine - * Copyright (c) 2007-2025 Diego Perini - * See http://nwbox.com/license - */ diff --git a/build/VERSION b/build/VERSION deleted file mode 100644 index 2f09892..0000000 --- a/build/VERSION +++ /dev/null @@ -1 +0,0 @@ -2.2.23 diff --git a/build/conf/jsl.conf b/build/conf/jsl.conf deleted file mode 100755 index 5385825..0000000 --- a/build/conf/jsl.conf +++ /dev/null @@ -1,123 +0,0 @@ -# -# Configuration File for JavaScript Lint 0.3.0 -# Developed by Matthias Miller (http://www.JavaScriptLint.com) -# -# This configuration file can be used to lint a collection of scripts, or to enable -# or disable warnings for scripts that are linted via the command line. -# - -### Warnings -# Enable or disable warnings based on requirements. -# Use "+WarningName" to display or "-WarningName" to suppress. -# --no_return_value # function {0} does not always return a value -+duplicate_formal # duplicate formal argument {0} --equal_as_assign # test for equality (==) mistyped as assignment (=)?{0} -+var_hides_arg # variable {0} hides argument -+redeclared_var # redeclaration of {0} {1} --anon_no_return_value # anonymous function does not always return a value --missing_semicolon # missing semicolon -+meaningless_block # meaningless block; curly braces have no impact -+comma_separated_stmts # multiple statements separated by commas (use semicolons?) -+unreachable_code # unreachable code -+missing_break # missing break statement -+missing_break_for_last_case # missing break statement for last case in switch --comparison_type_conv # comparisons against null, 0, true, false, or an empty string allowing implicit type conversion (use === or !==) --inc_dec_within_stmt # increment (++) and decrement (--) operators used as part of greater statement -+useless_void # use of the void type may be unnecessary (void is always undefined) -+multiple_plus_minus # unknown order of operations for successive plus (e.g. x+++y) or minus (e.g. x---y) signs -+use_of_label # use of label --block_without_braces # block statement without curly braces -+leading_decimal_point # leading decimal point may indicate a number or an object member -+trailing_decimal_point # trailing decimal point may indicate a number or an object member -+octal_number # leading zeros make an octal number -+nested_comment # nested comment -+misplaced_regex # regular expressions should be preceded by a left parenthesis, assignment, colon, or comma --ambiguous_newline # unexpected end of line; it is ambiguous whether these lines are part of the same statement -+empty_statement # empty statement or extra semicolon --missing_option_explicit # the "option explicit" control comment is missing -+partial_option_explicit # the "option explicit" control comment, if used, must be in the first script tag -+dup_option_explicit # duplicate "option explicit" control comment -+useless_assign # useless assignment --ambiguous_nested_stmt # block statements containing block statements should use curly braces to resolve ambiguity -+ambiguous_else_stmt # the else statement could be matched with one of multiple if statements (use curly braces to indicate intent) -+missing_default_case # missing default case in switch statement -+duplicate_case_in_switch # duplicate case in switch statements -+default_not_at_end # the default case is not at the end of the switch statement -+legacy_cc_not_understood # couldn't understand control comment using /*@keyword@*/ syntax -+jsl_cc_not_understood # couldn't understand control comment using /*jsl:keyword*/ syntax -+useless_comparison # useless comparison; comparing identical expressions -+with_statement # with statement hides undeclared variables; use temporary variable instead -+trailing_comma_in_array # extra comma is not recommended in array initializers -+assign_to_function_call # assignment to a function call -+parseint_missing_radix # parseInt missing radix parameter - - -### Output format -# Customize the format of the error message. -# __FILE__ indicates current file path -# __FILENAME__ indicates current file name -# __LINE__ indicates current line -# __ERROR__ indicates error message -# -# Visual Studio syntax (default): -+output-format __FILE__(__LINE__): __ERROR__ -# Alternative syntax: -#+output-format __FILE__:__LINE__: __ERROR__ - - -### Context -# Show the in-line position of the error. -# Use "+context" to display or "-context" to suppress. -# -+context - - -### Semicolons -# By default, assignments of an anonymous function to a variable or -# property (such as a function prototype) must be followed by a semicolon. -# -+lambda_assign_requires_semicolon - - -### Control Comments -# Both JavaScript Lint and the JScript interpreter confuse each other with the syntax for -# the /*@keyword@*/ control comments and JScript conditional comments. (The latter is -# enabled in JScript with @cc_on@). The /*jsl:keyword*/ syntax is preferred for this reason, -# although legacy control comments are enabled by default for backward compatibility. -# -+legacy_control_comments - - -### JScript Function Extensions -# JScript allows member functions to be defined like this: -# function MyObj() { /*constructor*/ } -# function MyObj.prototype.go() { /*member function*/ } -# -# It also allows events to be attached like this: -# function window::onload() { /*init page*/ } -# -# This is a Microsoft-only JavaScript extension. Enable this setting to allow them. -# --jscript_function_extensions - - -### Defining identifiers -# By default, "option explicit" is enabled on a per-file basis. -# To enable this for all files, use "+always_use_option_explicit" --always_use_option_explicit - -# Define certain identifiers of which the lint is not aware. -# (Use this in conjunction with the "undeclared identifier" warning.) -# -# Common uses for webpages might be: -#+define window -#+define document - -### Files -# Specify which files to lint -# Use "+recurse" to enable recursion (disabled by default). -# To add a set of files, use "+process FileName", "+process Folder\Path\*.js", -# or "+process Folder\Path\*.htm". -# -#+process jsl-test.js diff --git a/build/conf/jsl.default.conf b/build/conf/jsl.default.conf deleted file mode 100755 index 418c0c8..0000000 --- a/build/conf/jsl.default.conf +++ /dev/null @@ -1,123 +0,0 @@ -# -# Configuration File for JavaScript Lint 0.3.0 -# Developed by Matthias Miller (http://www.JavaScriptLint.com) -# -# This configuration file can be used to lint a collection of scripts, or to enable -# or disable warnings for scripts that are linted via the command line. -# - -### Warnings -# Enable or disable warnings based on requirements. -# Use "+WarningName" to display or "-WarningName" to suppress. -# -+no_return_value # function {0} does not always return a value -+duplicate_formal # duplicate formal argument {0} -+equal_as_assign # test for equality (==) mistyped as assignment (=)?{0} -+var_hides_arg # variable {0} hides argument -+redeclared_var # redeclaration of {0} {1} -+anon_no_return_value # anonymous function does not always return a value -+missing_semicolon # missing semicolon -+meaningless_block # meaningless block; curly braces have no impact -+comma_separated_stmts # multiple statements separated by commas (use semicolons?) -+unreachable_code # unreachable code -+missing_break # missing break statement -+missing_break_for_last_case # missing break statement for last case in switch -+comparison_type_conv # comparisons against null, 0, true, false, or an empty string allowing implicit type conversion (use === or !==) -+inc_dec_within_stmt # increment (++) and decrement (--) operators used as part of greater statement -+useless_void # use of the void type may be unnecessary (void is always undefined) -+multiple_plus_minus # unknown order of operations for successive plus (e.g. x+++y) or minus (e.g. x---y) signs -+use_of_label # use of label --block_without_braces # block statement without curly braces -+leading_decimal_point # leading decimal point may indicate a number or an object member -+trailing_decimal_point # trailing decimal point may indicate a number or an object member -+octal_number # leading zeros make an octal number -+nested_comment # nested comment -+misplaced_regex # regular expressions should be preceded by a left parenthesis, assignment, colon, or comma -+ambiguous_newline # unexpected end of line; it is ambiguous whether these lines are part of the same statement -+empty_statement # empty statement or extra semicolon --missing_option_explicit # the "option explicit" control comment is missing -+partial_option_explicit # the "option explicit" control comment, if used, must be in the first script tag -+dup_option_explicit # duplicate "option explicit" control comment -+useless_assign # useless assignment -+ambiguous_nested_stmt # block statements containing block statements should use curly braces to resolve ambiguity -+ambiguous_else_stmt # the else statement could be matched with one of multiple if statements (use curly braces to indicate intent) -+missing_default_case # missing default case in switch statement -+duplicate_case_in_switch # duplicate case in switch statements -+default_not_at_end # the default case is not at the end of the switch statement -+legacy_cc_not_understood # couldn't understand control comment using /*@keyword@*/ syntax -+jsl_cc_not_understood # couldn't understand control comment using /*jsl:keyword*/ syntax -+useless_comparison # useless comparison; comparing identical expressions -+with_statement # with statement hides undeclared variables; use temporary variable instead -+trailing_comma_in_array # extra comma is not recommended in array initializers -+assign_to_function_call # assignment to a function call -+parseint_missing_radix # parseInt missing radix parameter - - -### Output format -# Customize the format of the error message. -# __FILE__ indicates current file path -# __FILENAME__ indicates current file name -# __LINE__ indicates current line -# __ERROR__ indicates error message -# -# Visual Studio syntax (default): -+output-format __FILE__(__LINE__): __ERROR__ -# Alternative syntax: -#+output-format __FILE__:__LINE__: __ERROR__ - - -### Context -# Show the in-line position of the error. -# Use "+context" to display or "-context" to suppress. -# -+context - - -### Semicolons -# By default, assignments of an anonymous function to a variable or -# property (such as a function prototype) must be followed by a semicolon. -# -+lambda_assign_requires_semicolon - - -### Control Comments -# Both JavaScript Lint and the JScript interpreter confuse each other with the syntax for -# the /*@keyword@*/ control comments and JScript conditional comments. (The latter is -# enabled in JScript with @cc_on@). The /*jsl:keyword*/ syntax is preferred for this reason, -# although legacy control comments are enabled by default for backward compatibility. -# -+legacy_control_comments - - -### JScript Function Extensions -# JScript allows member functions to be defined like this: -# function MyObj() { /*constructor*/ } -# function MyObj.prototype.go() { /*member function*/ } -# -# It also allows events to be attached like this: -# function window::onload() { /*init page*/ } -# -# This is a Microsoft-only JavaScript extension. Enable this setting to allow them. -# --jscript_function_extensions - - -### Defining identifiers -# By default, "option explicit" is enabled on a per-file basis. -# To enable this for all files, use "+always_use_option_explicit" --always_use_option_explicit - -# Define certain identifiers of which the lint is not aware. -# (Use this in conjunction with the "undeclared identifier" warning.) -# -# Common uses for webpages might be: -#+define window -#+define document - -### Files -# Specify which files to lint -# Use "+recurse" to enable recursion (disabled by default). -# To add a set of files, use "+process FileName", "+process Folder\Path\*.js", -# or "+process Folder\Path\*.htm". -# -#+process jsl-test.js diff --git a/build/packer/base2.js b/build/packer/base2.js deleted file mode 100644 index 226453c..0000000 --- a/build/packer/base2.js +++ /dev/null @@ -1,1678 +0,0 @@ -/* - base2 - copyright 2007-2008, Dean Edwards - http://code.google.com/p/base2/ - http://www.opensource.org/licenses/mit-license.php - - Contributors: - Doeke Zanstra -*/ - -// timestamp: Sat, 06 Sep 2008 16:52:32 - -var base2 = { - name: "base2", - version: "1.0", - exports: - "Base,Package,Abstract,Module,Enumerable,Map,Collection,RegGrp," + - "Undefined,Null,This,True,False,assignID,detect,global", - namespace: "" -}; - -new function(_no_shrink_) { /////////////// BEGIN: CLOSURE /////////////// - -// ========================================================================= -// base2/header.js -// ========================================================================= - -var Undefined = K(), Null = K(null), True = K(true), False = K(false), This = function(){return this}; - -var global = This(); -var base2 = global.base2; - -// private -var _FORMAT = /%([1-9])/g; -var _LTRIM = /^\s\s*/; -var _RTRIM = /\s\s*$/; -var _RESCAPE = /([\/()[\]{}|*+-.,^$?\\])/g; // safe regular expressions -var _BASE = /try/.test(detect) ? /\bbase\b/ : /.*/; // some platforms don't allow decompilation -var _HIDDEN = ["constructor", "toString", "valueOf"]; // only override these when prototyping -var _MSIE_NATIVE_FUNCTION = detect("(jscript)") ? - new RegExp("^" + rescape(isNaN).replace(/isNaN/, "\\w+") + "$") : {test: False}; - -var _counter = 1; -var _slice = Array.prototype.slice; - -_Function_forEach(); // make sure this is initialised - -function assignID(object) { - // Assign a unique ID to an object. - if (!object.base2ID) object.base2ID = "b2_" + _counter++; - return object.base2ID; -}; - -// ========================================================================= -// base2/Base.js -// ========================================================================= - -// http://dean.edwards.name/weblog/2006/03/base/ - -var _subclass = function(_instance, _static) { - // Build the prototype. - base2.__prototyping = this.prototype; - var _prototype = new this; - if (_instance) extend(_prototype, _instance); - delete base2.__prototyping; - - // Create the wrapper for the constructor function. - var _constructor = _prototype.constructor; - function _class() { - // Don't call the constructor function when prototyping. - if (!base2.__prototyping) { - if (this.constructor == arguments.callee || this.__constructing) { - // Instantiation. - this.__constructing = true; - _constructor.apply(this, arguments); - delete this.__constructing; - } else { - // Casting. - return extend(arguments[0], _prototype); - } - } - return this; - }; - _prototype.constructor = _class; - - // Build the static interface. - for (var i in Base) _class[i] = this[i]; - _class.ancestor = this; - _class.base = Undefined; - //_class.init = Undefined; - if (_static) extend(_class, _static); - _class.prototype = _prototype; - if (_class.init) _class.init(); - - // introspection (removed when packed) - ;;; _class["#implements"] = []; - ;;; _class["#implemented_by"] = []; - - return _class; -}; - -var Base = _subclass.call(Object, { - constructor: function() { - if (arguments.length > 0) { - this.extend(arguments[0]); - } - }, - - base: function() { - // Call this method from any other method to invoke the current method's ancestor (super). - }, - - extend: delegate(extend) -}, Base = { - ancestorOf: function(klass) { - return _ancestorOf(this, klass); - }, - - extend: _subclass, - - forEach: function(object, block, context) { - _Function_forEach(this, object, block, context); - }, - - implement: function(source) { - if (typeof source == "function") { - ;;; if (_ancestorOf(Base, source)) { - // introspection (removed when packed) - ;;; this["#implements"].push(source); - ;;; source["#implemented_by"].push(this); - ;;; } - source = source.prototype; - } - // Add the interface using the extend() function. - extend(this.prototype, source); - return this; - } -}); - -// ========================================================================= -// base2/Package.js -// ========================================================================= - -var Package = Base.extend({ - constructor: function(_private, _public) { - this.extend(_public); - if (this.init) this.init(); - - if (this.name && this.name != "base2") { - if (!this.parent) this.parent = base2; - this.parent.addName(this.name, this); - this.namespace = format("var %1=%2;", this.name, String2.slice(this, 1, -1)); - } - - if (_private) { - // This next line gets round a bug in old Mozilla browsers - var JSNamespace = base2.JavaScript ? base2.JavaScript.namespace : ""; - // This string should be evaluated immediately after creating a Package object. - _private.imports = Array2.reduce(csv(this.imports), function(namespace, name) { - var ns = lookup(name) || lookup("JavaScript." + name); - ;;; assert(ns, format("Object not found: '%1'.", name), ReferenceError); - return namespace += ns.namespace; - }, "var base2=(function(){return this.base2})();" + base2.namespace + JSNamespace) + lang.namespace; - - // This string should be evaluated after you have created all of the objects - // that are being exported. - _private.exports = Array2.reduce(csv(this.exports), function(namespace, name) { - var fullName = this.name + "." + name; - this.namespace += "var " + name + "=" + fullName + ";"; - return namespace += "if(!" + fullName + ")" + fullName + "=" + name + ";"; - }, "", this) + "this._label_" + this.name + "();"; - - var pkg = this; - var packageName = String2.slice(this, 1, -1); - _private["_label_" + this.name] = function() { - Package.forEach (pkg, function(object, name) { - if (object && object.ancestorOf == Base.ancestorOf) { - object.toString = K(format("[%1.%2]", packageName, name)); - if (object.prototype.toString == Base.prototype.toString) { - object.prototype.toString = K(format("[object %1.%2]", packageName, name)); - } - } - }); - }; - } - - function lookup(names) { - names = names.split("."); - var value = base2, i = 0; - while (value && names[i] != null) { - value = value[names[i++]]; - } - return value; - }; - }, - - exports: "", - imports: "", - name: "", - namespace: "", - parent: null, - - addName: function(name, value) { - if (!this[name]) { - this[name] = value; - this.exports += "," + name; - this.namespace += format("var %1=%2.%1;", name, this.name); - } - }, - - addPackage: function(name) { - this.addName(name, new Package(null, {name: name, parent: this})); - }, - - toString: function() { - return format("[%1]", this.parent ? String2.slice(this.parent, 1, -1) + "." + this.name : this.name); - } -}); - -// ========================================================================= -// base2/Abstract.js -// ========================================================================= - -var Abstract = Base.extend({ - constructor: function() { - throw new TypeError("Abstract class cannot be instantiated."); - } -}); - -// ========================================================================= -// base2/Module.js -// ========================================================================= - -var _moduleCount = 0; - -var Module = Abstract.extend(null, { - namespace: "", - - extend: function(_interface, _static) { - // Extend a module to create a new module. - var module = this.base(); - var index = _moduleCount++; - module.namespace = ""; - module.partial = this.partial; - module.toString = K("[base2.Module[" + index + "]]"); - Module[index] = module; - // Inherit class methods. - module.implement(this); - // Implement module (instance AND static) methods. - if (_interface) module.implement(_interface); - // Implement static properties and methods. - if (_static) { - extend(module, _static); - if (module.init) module.init(); - } - return module; - }, - - forEach: function(block, context) { - _Function_forEach (Module, this.prototype, function(method, name) { - if (typeOf(method) == "function") { - block.call(context, this[name], name, this); - } - }, this); - }, - - implement: function(_interface) { - var module = this; - var id = module.toString().slice(1, -1); - if (typeof _interface == "function") { - if (!_ancestorOf(_interface, module)) { - this.base(_interface); - } - if (_ancestorOf(Module, _interface)) { - // Implement static methods. - for (var name in _interface) { - if (module[name] === undefined) { - var property = _interface[name]; - if (typeof property == "function" && property.call && _interface.prototype[name]) { - property = _staticModuleMethod(_interface, name); - } - module[name] = property; - } - } - module.namespace += _interface.namespace.replace(/base2\.Module\[\d+\]/g, id); - } - } else { - // Add static interface. - extend(module, _interface); - // Add instance interface. - _extendModule(module, _interface); - } - return module; - }, - - partial: function() { - var module = Module.extend(); - var id = module.toString().slice(1, -1); - // partial methods are already bound so remove the binding to speed things up - module.namespace = this.namespace.replace(/(\w+)=b[^\)]+\)/g, "$1=" + id + ".$1"); - this.forEach(function(method, name) { - module[name] = partial(bind(method, module)); - }); - return module; - } -}); - -function _extendModule(module, _interface) { - var proto = module.prototype; - var id = module.toString().slice(1, -1); - for (var name in _interface) { - var property = _interface[name], namespace = ""; - if (name.charAt(0) == "@") { // object detection - if (detect(name.slice(1))) _extendModule(module, property); - } else if (!proto[name]) { - if (name == name.toUpperCase()) { - namespace = "var " + name + "=" + id + "." + name + ";"; - } else if (typeof property == "function" && property.call) { - namespace = "var " + name + "=base2.lang.bind('" + name + "'," + id + ");"; - proto[name] = _moduleMethod(module, name); - ;;; proto[name]._module = module; // introspection - } - if (module.namespace.indexOf(namespace) == -1) { - module.namespace += namespace; - } - } - } -}; - -function _staticModuleMethod(module, name) { - return function() { - return module[name].apply(module, arguments); - }; -}; - -function _moduleMethod(module, name) { - return function() { - var args = _slice.call(arguments); - args.unshift(this); - return module[name].apply(module, args); - }; -}; - -// ========================================================================= -// base2/Enumerable.js -// ========================================================================= - -var Enumerable = Module.extend({ - every: function(object, test, context) { - var result = true; - try { - forEach (object, function(value, key) { - result = test.call(context, value, key, object); - if (!result) throw StopIteration; - }); - } catch (error) { - if (error != StopIteration) throw error; - } - return !!result; // cast to boolean - }, - - filter: function(object, test, context) { - var i = 0; - return this.reduce(object, function(result, value, key) { - if (test.call(context, value, key, object)) { - result[i++] = value; - } - return result; - }, []); - }, - - invoke: function(object, method) { - // Apply a method to each item in the enumerated object. - var args = _slice.call(arguments, 2); - return this.map(object, (typeof method == "function") ? function(item) { - return item == null ? undefined : method.apply(item, args); - } : function(item) { - return item == null ? undefined : item[method].apply(item, args); - }); - }, - - map: function(object, block, context) { - var result = [], i = 0; - forEach (object, function(value, key) { - result[i++] = block.call(context, value, key, object); - }); - return result; - }, - - pluck: function(object, key) { - return this.map(object, function(item) { - return item == null ? undefined : item[key]; - }); - }, - - reduce: function(object, block, result, context) { - var initialised = arguments.length > 2; - forEach (object, function(value, key) { - if (initialised) { - result = block.call(context, result, value, key, object); - } else { - result = value; - initialised = true; - } - }); - return result; - }, - - some: function(object, test, context) { - return !this.every(object, not(test), context); - } -}); - -// ========================================================================= -// base2/Map.js -// ========================================================================= - -// http://wiki.ecmascript.org/doku.php?id=proposals:dictionary - -var _HASH = "#"; - -var Map = Base.extend({ - constructor: function(values) { - if (values) this.merge(values); - }, - - clear: function() { - for (var key in this) if (key.indexOf(_HASH) == 0) { - delete this[key]; - } - }, - - copy: function() { - base2.__prototyping = true; // not really prototyping but it stops [[construct]] being called - var copy = new this.constructor; - delete base2.__prototyping; - for (var i in this) if (this[i] !== copy[i]) { - copy[i] = this[i]; - } - return copy; - }, - - forEach: function(block, context) { - for (var key in this) if (key.indexOf(_HASH) == 0) { - block.call(context, this[key], key.slice(1), this); - } - }, - - get: function(key) { - return this[_HASH + key]; - }, - - getKeys: function() { - return this.map(II); - }, - - getValues: function() { - return this.map(I); - }, - - // Ancient browsers throw an error if we use "in" as an operator. - has: function(key) { - /*@cc_on @*/ - /*@if (@_jscript_version < 5.5) - return $Legacy.has(this, _HASH + key); - @else @*/ - return _HASH + key in this; - /*@end @*/ - }, - - merge: function(values) { - var put = flip(this.put); - forEach (arguments, function(values) { - forEach (values, put, this); - }, this); - return this; - }, - - put: function(key, value) { - // create the new entry (or overwrite the old entry). - this[_HASH + key] = value; - }, - - remove: function(key) { - delete this[_HASH + key]; - }, - - size: function() { - // this is expensive because we are not storing the keys - var size = 0; - for (var key in this) if (key.indexOf(_HASH) == 0) size++; - return size; - }, - - union: function(values) { - return this.merge.apply(this.copy(), arguments); - } -}); - -Map.implement(Enumerable); - -Map.prototype.filter = function(test, context) { - return this.reduce(function(result, value, key) { - if (!test.call(context, value, key, this)) { - result.remove(key); - } - return result; - }, this.copy(), this); -}; - -// ========================================================================= -// base2/Collection.js -// ========================================================================= - -// A Map that is more array-like (accessible by index). - -// Collection classes have a special (optional) property: Item -// The Item property points to a constructor function. -// Members of the collection must be an instance of Item. - -// The static create() method is responsible for all construction of collection items. -// Instance methods that add new items (add, put, insertAt, putAt) pass *all* of their arguments -// to the static create() method. If you want to modify the way collection items are -// created then you only need to override this method for custom collections. - -var _KEYS = "~"; - -var Collection = Map.extend({ - constructor: function(values) { - this[_KEYS] = new Array2; - this.base(values); - }, - - add: function(key, item) { - // Duplicates not allowed using add(). - // But you can still overwrite entries using put(). - assert(!this.has(key), "Duplicate key '" + key + "'."); - this.put.apply(this, arguments); - }, - - clear: function() { - this.base(); - this[_KEYS].length = 0; - }, - - copy: function() { - var copy = this.base(); - copy[_KEYS] = this[_KEYS].copy(); - return copy; - }, - - forEach: function(block, context) { - var keys = this[_KEYS]; - var length = keys.length; - for (var i = 0; i < length; i++) { - block.call(context, this[_HASH + keys[i]], keys[i], this); - } - }, - - getAt: function(index) { - var key = this[_KEYS].item(index); - return (key === undefined) ? undefined : this[_HASH + key]; - }, - - getKeys: function() { - return this[_KEYS].copy(); - }, - - indexOf: function(key) { - return this[_KEYS].indexOf(String(key)); - }, - - insertAt: function(index, key, item) { - assert(this[_KEYS].item(index) !== undefined, "Index out of bounds."); - assert(!this.has(key), "Duplicate key '" + key + "'."); - this[_KEYS].insertAt(index, String(key)); - this[_HASH + key] = null; // placeholder - this.put.apply(this, _slice.call(arguments, 1)); - }, - - item: function(keyOrIndex) { - return this[typeof keyOrIndex == "number" ? "getAt" : "get"](keyOrIndex); - }, - - put: function(key, item) { - if (!this.has(key)) { - this[_KEYS].push(String(key)); - } - var klass = this.constructor; - if (klass.Item && !instanceOf(item, klass.Item)) { - item = klass.create.apply(klass, arguments); - } - this[_HASH + key] = item; - }, - - putAt: function(index, item) { - arguments[0] = this[_KEYS].item(index); - assert(arguments[0] !== undefined, "Index out of bounds."); - this.put.apply(this, arguments); - }, - - remove: function(key) { - // The remove() method of the Array object can be slow so check if the key exists first. - if (this.has(key)) { - this[_KEYS].remove(String(key)); - delete this[_HASH + key]; - } - }, - - removeAt: function(index) { - var key = this[_KEYS].item(index); - if (key !== undefined) { - this[_KEYS].removeAt(index); - delete this[_HASH + key]; - } - }, - - reverse: function() { - this[_KEYS].reverse(); - return this; - }, - - size: function() { - return this[_KEYS].length; - }, - - slice: function(start, end) { - var sliced = this.copy(); - if (arguments.length > 0) { - var keys = this[_KEYS], removed = keys; - sliced[_KEYS] = Array2(_slice.apply(keys, arguments)); - if (sliced[_KEYS].length) { - removed = removed.slice(0, start); - if (arguments.length > 1) { - removed = removed.concat(keys.slice(end)); - } - } - for (var i = 0; i < removed.length; i++) { - delete sliced[_HASH + removed[i]]; - } - } - return sliced; - }, - - sort: function(compare) { // optimised (refers to _HASH) - if (compare) { - this[_KEYS].sort(bind(function(key1, key2) { - return compare(this[_HASH + key1], this[_HASH + key2], key1, key2); - }, this)); - } else this[_KEYS].sort(); - return this; - }, - - toString: function() { - return "(" + (this[_KEYS] || "") + ")"; - } -}, { - Item: null, // If specified, all members of the collection must be instances of Item. - - create: function(key, item) { - return this.Item ? new this.Item(key, item) : item; - }, - - extend: function(_instance, _static) { - var klass = this.base(_instance); - klass.create = this.create; - if (_static) extend(klass, _static); - if (!klass.Item) { - klass.Item = this.Item; - } else if (typeof klass.Item != "function") { - klass.Item = (this.Item || Base).extend(klass.Item); - } - if (klass.init) klass.init(); - return klass; - } -}); - -// ========================================================================= -// base2/RegGrp.js -// ========================================================================= - -// A collection of regular expressions and their associated replacement values. -// A Base class for creating parsers. - -var _RG_BACK_REF = /\\(\d+)/g, - _RG_ESCAPE_CHARS = /\\./g, - _RG_ESCAPE_BRACKETS = /\(\?[:=!]|\[[^\]]+\]/g, - _RG_BRACKETS = /\(/g, - _RG_LOOKUP = /\$(\d+)/, - _RG_LOOKUP_SIMPLE = /^\$\d+$/; - -var RegGrp = Collection.extend({ - constructor: function(values, ignoreCase) { - this.base(values); - this.ignoreCase = !!ignoreCase; - }, - - ignoreCase: false, - - exec: function(string, override) { // optimised (refers to _HASH/_KEYS) - string += ""; // type-safe - var items = this, keys = this[_KEYS]; - if (!keys.length) return string; - if (override == RegGrp.IGNORE) override = 0; - return string.replace(new RegExp(this, this.ignoreCase ? "gi" : "g"), function(match) { - var item, offset = 1, i = 0; - // Loop through the RegGrp items. - while ((item = items[_HASH + keys[i++]])) { - var next = offset + item.length + 1; - if (arguments[offset]) { // do we have a result? - var replacement = override == null ? item.replacement : override; - switch (typeof replacement) { - case "function": - return replacement.apply(items, _slice.call(arguments, offset, next)); - case "number": - return arguments[offset + replacement]; - default: - return replacement; - } - } - offset = next; - } - return match; - }); - }, - - insertAt: function(index, expression, replacement) { - if (instanceOf(expression, RegExp)) { - arguments[1] = expression.source; - } - return base(this, arguments); - }, - - test: function(string) { - // The slow way to do it. Hopefully, this isn't called too often. :-) - return this.exec(string) != string; - }, - - toString: function() { - var offset = 1; - return "(" + this.map(function(item) { - // Fix back references. - var expression = (item + "").replace(_RG_BACK_REF, function(match, index) { - return "\\" + (offset + Number(index)); - }); - offset += item.length + 1; - return expression; - }).join(")|(") + ")"; - } -}, { - IGNORE: "$0", - - init: function() { - forEach ("add,get,has,put,remove".split(","), function(name) { - _override(this, name, function(expression) { - if (instanceOf(expression, RegExp)) { - arguments[0] = expression.source; - } - return base(this, arguments); - }); - }, this.prototype); - }, - - Item: { - constructor: function(expression, replacement) { - if (replacement == null) replacement = RegGrp.IGNORE; - else if (replacement.replacement != null) replacement = replacement.replacement; - else if (typeof replacement != "function") replacement = String(replacement); - - // does the pattern use sub-expressions? - if (typeof replacement == "string" && _RG_LOOKUP.test(replacement)) { - // a simple lookup? (e.g. "$2") - if (_RG_LOOKUP_SIMPLE.test(replacement)) { - // store the index (used for fast retrieval of matched strings) - replacement = parseInt(replacement.slice(1)); - } else { // a complicated lookup (e.g. "Hello $2 $1") - // build a function to do the lookup - // Improved version by Alexei Gorkov: - var Q = '"'; - replacement = replacement - .replace(/\\/g, "\\\\") - .replace(/"/g, "\\x22") - .replace(/\n/g, "\\n") - .replace(/\r/g, "\\r") - .replace(/\$(\d+)/g, Q + "+(arguments[$1]||" + Q+Q + ")+" + Q) - .replace(/(['"])\1\+(.*)\+\1\1$/, "$1"); - replacement = new Function("return " + Q + replacement + Q); - } - } - - this.length = RegGrp.count(expression); - this.replacement = replacement; - this.toString = K(expression + ""); - }, - - length: 0, - replacement: "" - }, - - count: function(expression) { - // Count the number of sub-expressions in a RegExp/RegGrp.Item. - expression = (expression + "").replace(_RG_ESCAPE_CHARS, "").replace(_RG_ESCAPE_BRACKETS, ""); - return match(expression, _RG_BRACKETS).length; - } -}); - -// ========================================================================= -// lang/package.js -// ========================================================================= - -var lang = { - name: "lang", - version: base2.version, - exports: "assert,assertArity,assertType,base,bind,copy,extend,forEach,format,instanceOf,match,pcopy,rescape,trim,typeOf", - namespace: "" // fixed later -}; - -// ========================================================================= -// lang/assert.js -// ========================================================================= - -function assert(condition, message, ErrorClass) { - if (!condition) { - throw new (ErrorClass || Error)(message || "Assertion failed."); - } -}; - -function assertArity(args, arity, message) { - if (arity == null) arity = args.callee.length; - if (args.length < arity) { - throw new SyntaxError(message || "Not enough arguments."); - } -}; - -function assertType(object, type, message) { - if (type && (typeof type == "function" ? !instanceOf(object, type) : typeOf(object) != type)) { - throw new TypeError(message || "Invalid type."); - } -}; - -// ========================================================================= -// lang/copy.js -// ========================================================================= - -function copy(object) { - // a quick copy - var copy = {}; - for (var i in object) { - copy[i] = object[i]; - } - return copy; -}; - -function pcopy(object) { - // Doug Crockford / Richard Cornford - _dummy.prototype = object; - return new _dummy; -}; - -function _dummy(){}; - -// ========================================================================= -// lang/extend.js -// ========================================================================= - -function base(object, args) { - return object.base.apply(object, args); -}; - -function extend(object, source) { // or extend(object, key, value) - if (object && source) { - if (arguments.length > 2) { // Extending with a key/value pair. - var key = source; - source = {}; - source[key] = arguments[2]; - } - var proto = global[(typeof source == "function" ? "Function" : "Object")].prototype; - // Add constructor, toString etc - if (base2.__prototyping) { - var i = _HIDDEN.length, key; - while ((key = _HIDDEN[--i])) { - var value = source[key]; - if (value != proto[key]) { - if (_BASE.test(value)) { - _override(object, key, value) - } else { - object[key] = value; - } - } - } - } - // Copy each of the source object's properties to the target object. - for (key in source) { - if (proto[key] === undefined) { - var value = source[key]; - // Object detection. - if (key.charAt(0) == "@") { - if (detect(key.slice(1))) extend(object, value); - } else { - // Check for method overriding. - var ancestor = object[key]; - if (ancestor && typeof value == "function") { - if (value != ancestor) { - if (_BASE.test(value)) { - _override(object, key, value); - } else { - value.ancestor = ancestor; - object[key] = value; - } - } - } else { - object[key] = value; - } - } - } - } - } - return object; -}; - -function _ancestorOf(ancestor, fn) { - // Check if a function is in another function's inheritance chain. - while (fn) { - if (!fn.ancestor) return false; - fn = fn.ancestor; - if (fn == ancestor) return true; - } - return false; -}; - -function _override(object, name, method) { - // Override an existing method. - var ancestor = object[name]; - var superObject = base2.__prototyping; // late binding for prototypes - if (superObject && ancestor != superObject[name]) superObject = null; - function _base() { - var previous = this.base; - this.base = superObject ? superObject[name] : ancestor; - var returnValue = method.apply(this, arguments); - this.base = previous; - return returnValue; - }; - _base.method = method; - _base.ancestor = ancestor; - object[name] = _base; - // introspection (removed when packed) - ;;; _base.toString = K(method + ""); -}; - -// ========================================================================= -// lang/forEach.js -// ========================================================================= - -// http://dean.edwards.name/weblog/2006/07/enum/ - -if (typeof StopIteration == "undefined") { - StopIteration = new Error("StopIteration"); -} - -function forEach(object, block, context, fn) { - if (object == null) return; - if (!fn) { - if (typeof object == "function" && object.call) { - // Functions are a special case. - fn = Function; - } else if (typeof object.forEach == "function" && object.forEach != arguments.callee) { - // The object implements a custom forEach method. - object.forEach(block, context); - return; - } else if (typeof object.length == "number") { - // The object is array-like. - _Array_forEach(object, block, context); - return; - } - } - _Function_forEach(fn || Object, object, block, context); -}; - -forEach.csv = function(string, block, context) { - forEach (csv(string), block, context); -}; - -forEach.detect = function(object, block, context) { - forEach (object, function(value, key) { - if (key.charAt(0) == "@") { // object detection - if (detect(key.slice(1))) forEach (value, arguments.callee); - } else block.call(context, value, key, object); - }); -}; - -// These are the two core enumeration methods. All other forEach methods -// eventually call one of these two. - -function _Array_forEach(array, block, context) { - if (array == null) array = global; - var length = array.length || 0, i; // preserve length - if (typeof array == "string") { - for (i = 0; i < length; i++) { - block.call(context, array.charAt(i), i, array); - } - } else { // Cater for sparse arrays. - for (i = 0; i < length; i++) { - /*@cc_on @*/ - /*@if (@_jscript_version < 5.2) - if ($Legacy.has(array, i)) - @else @*/ - if (i in array) - /*@end @*/ - block.call(context, array[i], i, array); - } - } -}; - -function _Function_forEach(fn, object, block, context) { - // http://code.google.com/p/base2/issues/detail?id=10 - - // Run the test for Safari's buggy enumeration. - var Temp = function(){this.i=1}; - Temp.prototype = {i:1}; - var count = 0; - for (var i in new Temp) count++; - - // Overwrite the main function the first time it is called. - _Function_forEach = (count > 1) ? function(fn, object, block, context) { - // Safari fix (pre version 3) - var processed = {}; - for (var key in object) { - if (!processed[key] && fn.prototype[key] === undefined) { - processed[key] = true; - block.call(context, object[key], key, object); - } - } - } : function(fn, object, block, context) { - // Enumerate an object and compare its keys with fn's prototype. - for (var key in object) { - if (fn.prototype[key] === undefined) { - block.call(context, object[key], key, object); - } - } - }; - - _Function_forEach(fn, object, block, context); -}; - -// ========================================================================= -// lang/instanceOf.js -// ========================================================================= - -function instanceOf(object, klass) { - // Handle exceptions where the target object originates from another frame. - // This is handy for JSON parsing (amongst other things). - - if (typeof klass != "function") { - throw new TypeError("Invalid 'instanceOf' operand."); - } - - if (object == null) return false; - - /*@cc_on - // COM objects don't have a constructor - if (typeof object.constructor != "function") { - return typeOf(object) == typeof klass.prototype.valueOf(); - } - @*/ - if (object.constructor == klass) return true; - if (klass.ancestorOf) return klass.ancestorOf(object.constructor); - /*@if (@_jscript_version < 5.1) - // do nothing - @else @*/ - if (object instanceof klass) return true; - /*@end @*/ - - // If the class is a base2 class then it would have passed the test above. - if (Base.ancestorOf == klass.ancestorOf) return false; - - // base2 objects can only be instances of Object. - if (Base.ancestorOf == object.constructor.ancestorOf) return klass == Object; - - switch (klass) { - case Array: // This is the only troublesome one. - return !!(typeof object == "object" && object.join && object.splice); - case Function: - return typeOf(object) == "function"; - case RegExp: - return typeof object.constructor.$1 == "string"; - case Date: - return !!object.getTimezoneOffset; - case String: - case Number: - case Boolean: - return typeOf(object) == typeof klass.prototype.valueOf(); - case Object: - return true; - } - - return false; -}; - -// ========================================================================= -// lang/typeOf.js -// ========================================================================= - -// http://wiki.ecmascript.org/doku.php?id=proposals:typeof - -function typeOf(object) { - var type = typeof object; - switch (type) { - case "object": - return object == null - ? "null" - : typeof object.constructor == "undefined" // COM object - ? _MSIE_NATIVE_FUNCTION.test(object) - ? "function" - : type - : typeof object.constructor.prototype.valueOf(); // underlying type - case "function": - return typeof object.call == "function" ? type : "object"; - default: - return type; - } -}; - -// ========================================================================= -// JavaScript/package.js -// ========================================================================= - -var JavaScript = { - name: "JavaScript", - version: base2.version, - exports: "Array2,Date2,Function2,String2", - namespace: "", // fixed later - - bind: function(host) { - var top = global; - global = host; - forEach.csv(this.exports, function(name2) { - var name = name2.slice(0, -1); - extend(host[name], this[name2]); - this[name2](host[name].prototype); // cast - }, this); - global = top; - return host; - } -}; - -function _createObject2(Native, constructor, generics, extensions) { - // Clone native objects and extend them. - - // Create a Module that will contain all the new methods. - var INative = Module.extend(); - var id = INative.toString().slice(1, -1); - // http://developer.mozilla.org/en/docs/New_in_JavaScript_1.6#Array_and_String_generics - forEach.csv(generics, function(name) { - INative[name] = unbind(Native.prototype[name]); - INative.namespace += format("var %1=%2.%1;", name, id); - }); - forEach (_slice.call(arguments, 3), INative.implement, INative); - - // create a faux constructor that augments the native object - var Native2 = function() { - return INative(this.constructor == INative ? constructor.apply(null, arguments) : arguments[0]); - }; - Native2.prototype = INative.prototype; - - // Remove methods that are already implemented. - for (var name in INative) { - if (name != "prototype" && Native[name]) { - INative[name] = Native[name]; - delete INative.prototype[name]; - } - Native2[name] = INative[name]; - } - Native2.ancestor = Object; - delete Native2.extend; - - // remove "lang.bind.." - Native2.namespace = Native2.namespace.replace(/(var (\w+)=)[^,;]+,([^\)]+)\)/g, "$1$3.$2"); - - return Native2; -}; - -// ========================================================================= -// JavaScript/~/Date.js -// ========================================================================= - -// Fix Date.get/setYear() (IE5-7) - -if ((new Date).getYear() > 1900) { - Date.prototype.getYear = function() { - return this.getFullYear() - 1900; - }; - Date.prototype.setYear = function(year) { - return this.setFullYear(year + 1900); - }; -} - -// https://bugs.webkit.org/show_bug.cgi?id=9532 - -var _testDate = new Date(Date.UTC(2006, 1, 20)); -_testDate.setUTCDate(15); -if (_testDate.getUTCHours() != 0) { - forEach.csv("FullYear,Month,Date,Hours,Minutes,Seconds,Milliseconds", function(type) { - extend(Date.prototype, "setUTC" + type, function() { - var value = base(this, arguments); - if (value >= 57722401000) { - value -= 3600000; - this.setTime(value); - } - return value; - }); - }); -} - -// ========================================================================= -// JavaScript/~/Function.js -// ========================================================================= - -// Some browsers don't define this. - -Function.prototype.prototype = {}; - -// ========================================================================= -// JavaScript/~/String.js -// ========================================================================= - -// A KHTML bug. - -if ("".replace(/^/, K("$$")) == "$") { - extend(String.prototype, "replace", function(expression, replacement) { - if (typeof replacement == "function") { - var fn = replacement; - replacement = function() { - return String(fn.apply(null, arguments)).split("$").join("$$"); - }; - } - return this.base(expression, replacement); - }); -} - -// ========================================================================= -// JavaScript/Array2.js -// ========================================================================= - -var Array2 = _createObject2( - Array, - Array, - "concat,join,pop,push,reverse,shift,slice,sort,splice,unshift", // generics - Enumerable, { - combine: function(keys, values) { - // Combine two arrays to make a hash. - if (!values) values = keys; - return Array2.reduce(keys, function(hash, key, index) { - hash[key] = values[index]; - return hash; - }, {}); - }, - - contains: function(array, item) { - return Array2.indexOf(array, item) != -1; - }, - - copy: function(array) { - var copy = _slice.call(array); - if (!copy.swap) Array2(copy); // cast to Array2 - return copy; - }, - - flatten: function(array) { - var i = 0; - return Array2.reduce(array, function(result, item) { - if (Array2.like(item)) { - Array2.reduce(item, arguments.callee, result); - } else { - result[i++] = item; - } - return result; - }, []); - }, - - forEach: _Array_forEach, - - indexOf: function(array, item, fromIndex) { - var length = array.length; - if (fromIndex == null) { - fromIndex = 0; - } else if (fromIndex < 0) { - fromIndex = Math.max(0, length + fromIndex); - } - for (var i = fromIndex; i < length; i++) { - if (array[i] === item) return i; - } - return -1; - }, - - insertAt: function(array, index, item) { - Array2.splice(array, index, 0, item); - return item; - }, - - item: function(array, index) { - if (index < 0) index += array.length; // starting from the end - return array[index]; - }, - - lastIndexOf: function(array, item, fromIndex) { - var length = array.length; - if (fromIndex == null) { - fromIndex = length - 1; - } else if (fromIndex < 0) { - fromIndex = Math.max(0, length + fromIndex); - } - for (var i = fromIndex; i >= 0; i--) { - if (array[i] === item) return i; - } - return -1; - }, - - map: function(array, block, context) { - var result = []; - Array2.forEach (array, function(item, index) { - result[index] = block.call(context, item, index, array); - }); - return result; - }, - - remove: function(array, item) { - var index = Array2.indexOf(array, item); - if (index != -1) Array2.removeAt(array, index); - }, - - removeAt: function(array, index) { - Array2.splice(array, index, 1); - }, - - swap: function(array, index1, index2) { - if (index1 < 0) index1 += array.length; // starting from the end - if (index2 < 0) index2 += array.length; - var temp = array[index1]; - array[index1] = array[index2]; - array[index2] = temp; - return array; - } - } -); - -Array2.reduce = Enumerable.reduce; // Mozilla does not implement the thisObj argument - -Array2.like = function(object) { - // is the object like an array? - return typeOf(object) == "object" && typeof object.length == "number"; -}; - -// introspection (removed when packed) -;;; Enumerable["#implemented_by"].pop(); -;;; Enumerable["#implemented_by"].push(Array2); - -// ========================================================================= -// JavaScript/Date2.js -// ========================================================================= - -// http://developer.mozilla.org/es4/proposals/date_and_time.html - -// big, ugly, regular expression -var _DATE_PATTERN = /^((-\d+|\d{4,})(-(\d{2})(-(\d{2}))?)?)?T((\d{2})(:(\d{2})(:(\d{2})(\.(\d{1,3})(\d)?\d*)?)?)?)?(([+-])(\d{2})(:(\d{2}))?|Z)?$/; -var _DATE_PARTS = { // indexes to the sub-expressions of the RegExp above - FullYear: 2, - Month: 4, - Date: 6, - Hours: 8, - Minutes: 10, - Seconds: 12, - Milliseconds: 14 -}; -var _TIMEZONE_PARTS = { // idem, but without the getter/setter usage on Date object - Hectomicroseconds: 15, // :-P - UTC: 16, - Sign: 17, - Hours: 18, - Minutes: 20 -}; - -var _TRIM_ZEROES = /(((00)?:0+)?:0+)?\.0+$/; -var _TRIM_TIMEZONE = /(T[0-9:.]+)$/; - -var Date2 = _createObject2( - Date, - function(yy, mm, dd, h, m, s, ms) { - switch (arguments.length) { - case 0: return new Date; - case 1: return typeof yy == "number" ? new Date(yy) : Date2.parse(yy); - default: return new Date(yy, mm, arguments.length == 2 ? 1 : dd, h || 0, m || 0, s || 0, ms || 0); - } - }, "", { - toISOString: function(date) { - var string = "####-##-##T##:##:##.###"; - for (var part in _DATE_PARTS) { - string = string.replace(/#+/, function(digits) { - var value = date["getUTC" + part](); - if (part == "Month") value++; // js month starts at zero - return ("000" + value).slice(-digits.length); // pad - }); - } - // remove trailing zeroes, and remove UTC timezone, when time's absent - return string.replace(_TRIM_ZEROES, "").replace(_TRIM_TIMEZONE, "$1Z"); - } - } -); - -delete Date2.forEach; - -Date2.now = function() { - return (new Date).valueOf(); // milliseconds since the epoch -}; - -Date2.parse = function(string, defaultDate) { - if (arguments.length > 1) { - assertType(defaultDate, "number", "default date should be of type 'number'.") - } - // parse ISO date - var parts = match(string, _DATE_PATTERN); - if (parts.length) { - if (parts[_DATE_PARTS.Month]) parts[_DATE_PARTS.Month]--; // js months start at zero - // round milliseconds on 3 digits - if (parts[_TIMEZONE_PARTS.Hectomicroseconds] >= 5) parts[_DATE_PARTS.Milliseconds]++; - var date = new Date(defaultDate || 0); - var prefix = parts[_TIMEZONE_PARTS.UTC] || parts[_TIMEZONE_PARTS.Hours] ? "UTC" : ""; - for (var part in _DATE_PARTS) { - var value = parts[_DATE_PARTS[part]]; - if (!value) continue; // empty value - // set a date part - date["set" + prefix + part](value); - // make sure that this setting does not overflow - if (date["get" + prefix + part]() != parts[_DATE_PARTS[part]]) { - return NaN; - } - } - // timezone can be set, without time being available - // without a timezone, local timezone is respected - if (parts[_TIMEZONE_PARTS.Hours]) { - var hours = Number(parts[_TIMEZONE_PARTS.Sign] + parts[_TIMEZONE_PARTS.Hours]); - var minutes = Number(parts[_TIMEZONE_PARTS.Sign] + (parts[_TIMEZONE_PARTS.Minutes] || 0)); - date.setUTCMinutes(date.getUTCMinutes() + (hours * 60) + minutes); - } - return date.valueOf(); - } else { - return Date.parse(string); - } -}; - -// ========================================================================= -// JavaScript/String2.js -// ========================================================================= - -var String2 = _createObject2( - String, - function(string) { - return new String(arguments.length == 0 ? "" : string); - }, - "charAt,charCodeAt,concat,indexOf,lastIndexOf,match,replace,search,slice,split,substr,substring,toLowerCase,toUpperCase", - { - csv: csv, - format: format, - rescape: rescape, - trim: trim - } -); - -delete String2.forEach; - -// http://blog.stevenlevithan.com/archives/faster-trim-javascript -function trim(string) { - return String(string).replace(_LTRIM, "").replace(_RTRIM, ""); -}; - -function csv(string) { - return string ? (string + "").split(/\s*,\s*/) : []; -}; - -function format(string) { - // Replace %n with arguments[n]. - // e.g. format("%1 %2%3 %2a %1%3", "she", "se", "lls"); - // ==> "she sells sea shells" - // Only %1 - %9 supported. - var args = arguments; - var pattern = new RegExp("%([1-" + (arguments.length - 1) + "])", "g"); - return (string + "").replace(pattern, function(match, index) { - return args[index]; - }); -}; - -function match(string, expression) { - // Same as String.match() except that this function will return an empty - // array if there is no match. - return (string + "").match(expression) || []; -}; - -function rescape(string) { - // Make a string safe for creating a RegExp. - return (string + "").replace(_RESCAPE, "\\$1"); -}; - -// ========================================================================= -// JavaScript/Function2.js -// ========================================================================= - -var Function2 = _createObject2( - Function, - Function, - "", { - I: I, - II: II, - K: K, - bind: bind, - compose: compose, - delegate: delegate, - flip: flip, - not: not, - partial: partial, - unbind: unbind - } -); - -function I(i) { // return first argument - return i; -}; - -function II(i, ii) { // return second argument - return ii; -}; - -function K(k) { - return function() { - return k; - }; -}; - -function bind(fn, context) { - var lateBound = typeof fn != "function"; - if (arguments.length > 2) { - var args = _slice.call(arguments, 2); - return function() { - return (lateBound ? context[fn] : fn).apply(context, args.concat.apply(args, arguments)); - }; - } else { // faster if there are no additional arguments - return function() { - return (lateBound ? context[fn] : fn).apply(context, arguments); - }; - } -}; - -function compose() { - var fns = _slice.call(arguments); - return function() { - var i = fns.length, result = fns[--i].apply(this, arguments); - while (i--) result = fns[i].call(this, result); - return result; - }; -}; - -function delegate(fn, context) { - return function() { - var args = _slice.call(arguments); - args.unshift(this); - return fn.apply(context, args); - }; -}; - -function flip(fn) { - return function() { - return fn.apply(this, Array2.swap(arguments, 0, 1)); - }; -}; - -function not(fn) { - return function() { - return !fn.apply(this, arguments); - }; -}; - -function partial(fn) { - var args = _slice.call(arguments, 1); - // based on Oliver Steele's version - return function() { - var specialised = args.concat(), i = 0, j = 0; - while (i < args.length && j < arguments.length) { - if (specialised[i] === undefined) specialised[i] = arguments[j++]; - i++; - } - while (j < arguments.length) { - specialised[i++] = arguments[j++]; - } - if (Array2.contains(specialised, undefined)) { - specialised.unshift(fn); - return partial.apply(null, specialised); - } - return fn.apply(this, specialised); - }; -}; - -function unbind(fn) { - return function(context) { - return fn.apply(context, _slice.call(arguments, 1)); - }; -}; - -// ========================================================================= -// base2/detect.js -// ========================================================================= - -function detect() { - // Two types of detection: - // 1. Object detection - // e.g. detect("(java)"); - // e.g. detect("!(document.addEventListener)"); - // 2. Platform detection (browser sniffing) - // e.g. detect("MSIE"); - // e.g. detect("MSIE|opera"); - - var jscript = NaN/*@cc_on||@_jscript_version@*/; // http://dean.edwards.name/weblog/2007/03/sniff/#comment85164 - var javaEnabled = global.java ? true : false; - if (global.navigator) { // browser - var MSIE = /MSIE[\d.]+/g; - var element = document.createElement("span"); - // Close up the space between name and version number. - // e.g. MSIE 6 -> MSIE6 - var userAgent = navigator.userAgent.replace(/([a-z])[\s\/](\d)/gi, "$1$2"); - // Fix opera's (and others) user agent string. - if (!jscript) userAgent = userAgent.replace(MSIE, ""); - if (MSIE.test(userAgent)) userAgent = userAgent.match(MSIE)[0] + " " + userAgent.replace(MSIE, ""); - base2.userAgent = navigator.platform + " " + userAgent.replace(/like \w+/gi, ""); - javaEnabled &= navigator.javaEnabled(); -//} else if (java) { // rhino -// var System = java.lang.System; -// base2.userAgent = "Rhino " + System.getProperty("os.arch") + " " + System.getProperty("os.name") + " " + System.getProperty("os.version"); -//} else if (jscript) { // Windows Scripting Host -// base2.userAgent = "WSH"; - } - - var _cache = {}; - detect = function(expression) { - if (_cache[expression] == null) { - var returnValue = false, test = expression; - var not = test.charAt(0) == "!"; - if (not) test = test.slice(1); - if (test.charAt(0) == "(") { - try { - returnValue = new Function("element,jscript,java,global", "return !!" + test)(element, jscript, javaEnabled, global); - } catch (ex) { - // the test failed - } - } else { - // Browser sniffing. - returnValue = new RegExp("(" + test + ")", "i").test(base2.userAgent); - } - _cache[expression] = !!(not ^ returnValue); - } - return _cache[expression]; - }; - - return detect(arguments[0]); -}; - -// ========================================================================= -// base2/init.js -// ========================================================================= - -base2 = global.base2 = new Package(this, base2); -var exports = this.exports; - -lang = new Package(this, lang); -exports += this.exports; - -JavaScript = new Package(this, JavaScript); -eval(exports + this.exports); - -lang.base = base; -lang.extend = extend; - -}; //////////////////// END: CLOSURE ///////////////////////////////////// diff --git a/build/packer/packer.js b/build/packer/packer.js deleted file mode 100644 index 7a3bada..0000000 --- a/build/packer/packer.js +++ /dev/null @@ -1,559 +0,0 @@ -/* - Packer version 3.1 - copyright 2004-2008, Dean Edwards - http://www.opensource.org/licenses/mit-license.php -*/ - -// timestamp: Mon, 30 Mar 2009 18:26:18 - -new function() { /////////////// BEGIN: CLOSURE /////////////// - -new base2.Package(this, { - imports: "Function2,Enumerable" -}); - -eval(this.imports); - -var IGNORE = RegGrp.IGNORE; -var KEYS = "~"; -var REMOVE = ""; -var SPACE = " "; - -// ========================================================================= -// packer/Parser.js -// ========================================================================= - -var Parser = RegGrp.extend({ - put: function(expression, replacement) { - if (typeOf(expression) == "string") { - expression = Parser.dictionary.exec(expression); - } - this.base(expression, replacement); - } -}, { - dictionary: new RegGrp({ - OPERATOR: /return|typeof|[\[(\^=,{}:;&|!*?]/.source, - CONDITIONAL: /\/\*@\w*|\w*@\*\/|\/\/@\w*|@\w+/.source, - COMMENT1: /\/\/[^\n]*/.source, - COMMENT2: /\/\*[^*]*\*+([^\/][^*]*\*+)*\//.source, - REGEXP: /\/(\\[\/\\]|[^*\/])(\\.|[^\/\n\\])*\/[gim]*/.source, - STRING1: /'(\\.|[^'\\])*'/.source, - STRING2: /"(\\.|[^"\\])*"/.source - }) -}); - -// ========================================================================= -// packer/Words.js -// ========================================================================= - -var Words = Collection.extend({ - add: function(word) { - if (!this.has(word)) this.base(word); - word = this.get(word); - if (!word.index) { - word.index = this.size(); - } - word.count++; - return word; - }, - - sort: function(sorter) { - return this.base(sorter || function(word1, word2) { - // sort by frequency - return (word2.count - word1.count) || (word1.index - word2.index); - }); - } -}, { - Item: { - constructor: function(word) { - this.toString = K(word); - }, - - index: 0, - count: 0, - encoded: "" - } -}); - -// ========================================================================= -// packer/Encoder.js -// ========================================================================= - -var Encoder = Base.extend({ - constructor: function(pattern, encoder, ignore) { - this.parser = new Parser(ignore); - if (pattern) this.parser.put(pattern, ""); - this.encoder = encoder; - }, - - parser: null, - encoder: Undefined, - - search: function(script) { - var words = new Words; - this.parser.putAt(-1, function(word) { - words.add(word); - }); - this.parser.exec(script); - return words; - }, - - encode: function(script) { - var words = this.search(script); - words.sort(); - var index = 0; - forEach (words, function(word) { - word.encoded = this.encoder(index++); - }, this); - this.parser.putAt(-1, function(word) { - return words.get(word).encoded; - }); - return this.parser.exec(script); - } -}); - -// ========================================================================= -// packer/Privates.js -// ========================================================================= - -var Privates = Encoder.extend({ - constructor: function() { - return this.base(Privates.PATTERN, function(index) { - return "_" + Packer.encode62(index); - }, Privates.IGNORE); - } -}, { - IGNORE: { - CONDITIONAL: IGNORE, - "(OPERATOR)(REGEXP)": IGNORE - }, - - PATTERN: /\b_[\da-zA-Z$][\w$]*\b/g -}); - -// ========================================================================= -// packer/Base62.js -// ========================================================================= - -var Base62 = Encoder.extend({ - encode: function(script) { - var words = this.search(script); - - words.sort(); - - var encoded = new Collection; // a dictionary of base62 -> base10 - var size = words.size(); - for (var i = 0; i < size; i++) { - encoded.put(Packer.encode62(i), i); - } - - function replacement(word) { - return words["#" + word].replacement; - }; - - var empty = K(""); - var index = 0; - forEach (words, function(word) { - if (encoded.has(word)) { - word.index = encoded.get(word); - word.toString = empty; - } else { - while (words.has(Packer.encode62(index))) index++; - word.index = index++; - if (word.count == 1) { - word.toString = empty; - } - } - word.replacement = Packer.encode62(word.index); - if (word.replacement.length == word.toString().length) { - word.toString = empty; - } - }); - - // sort by encoding - words.sort(function(word1, word2) { - return word1.index - word2.index; - }); - - // trim unencoded words - words = words.slice(0, this.getKeyWords(words).split("|").length); - - script = script.replace(this.getPattern(words), replacement); - - /* build the packed script */ - - var p = this.escape(script); - var a = "[]"; - var c = this.getCount(words); - var k = this.getKeyWords(words); - var e = this.getEncoder(words); - var d = this.getDecoder(words); - - // the whole thing - return format(Base62.UNPACK, p,a,c,k,e,d); - }, - - search: function(script) { - var words = new Words; - forEach (script.match(Base62.WORDS), words.add, words); - return words; - }, - - escape: function(script) { - // Single quotes wrap the final string so escape them. - // Also, escape new lines (required by conditional comments). - return script.replace(/([\\'])/g, "\\$1").replace(/[\r\n]+/g, "\\n"); - }, - - getCount: function(words) { - return words.size() || 1; - }, - - getDecoder: function(words) { - // returns a pattern used for fast decoding of the packed script - var trim = new RegGrp({ - "(\\d)(\\|\\d)+\\|(\\d)": "$1-$3", - "([a-z])(\\|[a-z])+\\|([a-z])": "$1-$3", - "([A-Z])(\\|[A-Z])+\\|([A-Z])": "$1-$3", - "\\|": "" - }); - var pattern = trim.exec(words.map(function(word) { - if (word.toString()) return word.replacement; - return ""; - }).slice(0, 62).join("|")); - - if (!pattern) return "^$"; - - pattern = "[" + pattern + "]"; - - var size = words.size(); - if (size > 62) { - pattern = "(" + pattern + "|"; - var c = Packer.encode62(size).charAt(0); - if (c > "9") { - pattern += "[\\\\d"; - if (c >= "a") { - pattern += "a"; - if (c >= "z") { - pattern += "-z"; - if (c >= "A") { - pattern += "A"; - if (c > "A") pattern += "-" + c; - } - } else if (c == "b") { - pattern += "-" + c; - } - } - pattern += "]"; - } else if (c == 9) { - pattern += "\\\\d"; - } else if (c == 2) { - pattern += "[12]"; - } else if (c == 1) { - pattern += "1"; - } else { - pattern += "[1-" + c + "]"; - } - - pattern += "\\\\w)"; - } - return pattern; - }, - - getEncoder: function(words) { - var size = words.size(); - return Base62["ENCODE" + (size > 10 ? size > 36 ? 62 : 36 : 10)]; - }, - - getKeyWords: function(words) { - return words.map(String).join("|").replace(/\|+$/, ""); - }, - - getPattern: function(words) { - words = words.map(String).join("|").replace(/\|{2,}/g, "|").replace(/^\|+|\|+$/g, "") || "\\x0"; - return new RegExp("\\b(" + words + ")\\b", "g"); - } -}, { - WORDS: /\b[\da-zA-Z]\b|\w{2,}/g, - - ENCODE10: "String", - ENCODE36: "function(c){return c.toString(36)}", - ENCODE62: "function(c){return(c<62?'':e(parseInt(c/62)))+((c=c%62)>35?String.fromCharCode(c+29):c.toString(36))}", - - UNPACK: "eval(function(p,a,c,k,e,r){e=%5;if('0'.replace(0,e)==0){while(c--)r[e(c)]=k[c];" + - "k=[function(e){return r[e]||e}];e=function(){return'%6'};c=1};while(c--)if(k[c])p=p." + - "replace(new RegExp('\\\\b'+e(c)+'\\\\b','g'),k[c]);return p}('%1',%2,%3,'%4'.split('|'),0,{}))" -}); - -// ========================================================================= -// packer/Packer.js -// ========================================================================= - -global.Packer = Base.extend({ - constructor: function() { - this.minifier = new Minifier; - this.shrinker = new Shrinker; - this.privates = new Privates; - this.base62 = new Base62; - }, - - minifier: null, - shrinker: null, - privates: null, - base62: null, - - pack: function(script, base62, shrink, privates) { - script = this.minifier.minify(script); - if (shrink) script = this.shrinker.shrink(script); - if (privates) script = this.privates.encode(script); - if (base62) script = this.base62.encode(script); - return script; - } -}, { - version: "3.1", - - init: function() { - eval("var e=this.encode62=" + Base62.ENCODE62); - }, - - data: new Parser({ - "STRING1": IGNORE, - 'STRING2': IGNORE, - "CONDITIONAL": IGNORE, // conditional comments - "(OPERATOR)\\s*(REGEXP)": "$1$2" - }), - - encode52: function(c) { - // Base52 encoding (a-Z) - function encode(c) { - return (c < 52 ? '' : encode(parseInt(c / 52))) + - ((c = c % 52) > 25 ? String.fromCharCode(c + 39) : String.fromCharCode(c + 97)); - }; - var encoded = encode(c); - if (/^(do|if|in)$/.test(encoded)) encoded = encoded.slice(1) + 0; - return encoded; - } -}); - -// ========================================================================= -// packer/Minifier.js -// ========================================================================= - -var Minifier = Base.extend({ - minify: function(script) { - // packing with no additional options - script += "\n"; - script = script.replace(Minifier.CONTINUE, ""); - script = Minifier.comments.exec(script); - script = Minifier.clean.exec(script); - script = Minifier.whitespace.exec(script); - script = Minifier.concat.exec(script); - return script; - } -}, { - CONTINUE: /\\\r?\n/g, - - init: function() { - this.concat = new Parser(this.concat).merge(Packer.data); - extend(this.concat, "exec", function(script) { - var parsed = this.base(script); - while (parsed != script) { - script = parsed; - parsed = this.base(script); - } - return parsed; - }); - forEach.csv("comments,clean,whitespace", function(name) { - this[name] = Packer.data.union(new Parser(this[name])); - }, this); - this.conditionalComments = this.comments.copy(); - this.conditionalComments.putAt(-1, " $3"); - this.whitespace.removeAt(2); // conditional comments - this.comments.removeAt(2); - }, - - clean: { - "\\(\\s*([^;)]*)\\s*;\\s*([^;)]*)\\s*;\\s*([^;)]*)\\)": "($1;$2;$3)", // for (;;) loops - "throw[^};]+[};]": IGNORE, // a safari 1.3 bug - ";+\\s*([};])": "$1" - }, - - comments: { - ";;;[^\\n]*\\n": REMOVE, - "(COMMENT1)\\n\\s*(REGEXP)?": "\n$3", - "(COMMENT2)\\s*(REGEXP)?": function(match, comment, $2, regexp) { - if (/^\/\*@/.test(comment) && /@\*\/$/.test(comment)) { - comment = Minifier.conditionalComments.exec(comment); - } else { - comment = ""; - } - return comment + " " + (regexp || ""); - } - }, - - concat: { - "(STRING1)\\+(STRING1)": function(match, a, $2, b) { - return a.slice(0, -1) + b.slice(1); - }, - "(STRING2)\\+(STRING2)": function(match, a, $2, b) { - return a.slice(0, -1) + b.slice(1); - } - }, - - whitespace: { - "\\/\\/@[^\\n]*\\n": IGNORE, - "@\\s+\\b": "@ ", // protect conditional comments - "\\b\\s+@": " @", - "(\\d)\\s+(\\.\\s*[a-z\\$_\\[(])": "$1 $2", // http://dean.edwards.name/weblog/2007/04/packer3/#comment84066 - "([+-])\\s+([+-])": "$1 $2", // c = a++ +b; - "(\\w)\\s+([\\u0080-\\uffff])": "$1 $2", // http://code.google.com/p/base2/issues/detail?id=78 - "\\b\\s+\\$\\s+\\b": " $ ", // var $ in - "\\$\\s+\\b": "$ ", // object$ in - "\\b\\s+\\$": " $", // return $object -// "\\b\\s+#": " #", // CSS - "\\b\\s+\\b": SPACE, - "\\s+": REMOVE - } -}); - -// ========================================================================= -// packer/Shrinker.js -// ========================================================================= - -var Shrinker = Base.extend({ - decodeData: function(script) { - // put strings and regular expressions back - var data = this._data; // encoded strings and regular expressions - delete this._data; - return script.replace(Shrinker.ENCODED_DATA, function(match, index) { - return data[index]; - }); - }, - - encodeData: function(script) { - // encode strings and regular expressions - var data = this._data = []; // encoded strings and regular expressions - return Packer.data.exec(script, function(match, operator, regexp) { - var replacement = "\x01" + data.length + "\x01"; - if (regexp) { - replacement = operator + replacement; - match = regexp; - } - data.push(match); - return replacement; - }); - }, - - shrink: function(script) { - script = this.encodeData(script); - - // Windows Scripting Host cannot do regexp.test() on global regexps. - function global(regexp) { - // This function creates a global version of the passed regexp. - return new RegExp(regexp.source, "g"); - }; - - // identify blocks, particularly identify function blocks (which define scope) - var BLOCK = /((catch|do|if|while|with|function)\b[^~{};]*(\(\s*[^{};]*\s*\))\s*)?(\{[^{}]*\})/; - var BLOCK_g = global(BLOCK); - var BRACKETS = /\{[^{}]*\}|\[[^\[\]]*\]|\([^\(\)]*\)|~[^~]+~/; - var BRACKETS_g = global(BRACKETS); - var ENCODED_BLOCK = /~#?(\d+)~/; - var IDENTIFIER = /[a-zA-Z_$][\w\$]*/g; - var SCOPED = /~#(\d+)~/; - var VAR_g = /\bvar\b/g; - var VARS = /\bvar\s+[\w$]+[^;#]*|\bfunction\s+[\w$]+/g; - var VAR_TIDY = /\b(var|function)\b|\sin\s+[^;]+/g; - var VAR_EQUAL = /\s*=[^,;]*/g; - - var blocks = []; // store program blocks (anything between braces {}) - var total = 0; - // encoder for program blocks - function encodeBlocks($, prefix, blockType, args, block) { - if (!prefix) prefix = ""; - if (blockType == "function") { - // decode the function block (THIS IS THE IMPORTANT BIT) - // We are retrieving all sub-blocks and will re-parse them in light - // of newly shrunk variables - block = args + decodeBlocks(block, SCOPED); - prefix = prefix.replace(BRACKETS, ""); - - // create the list of variable and argument names - args = args.slice(1, -1); - - if (args != "_no_shrink_") { - var vars = match(block, VARS).join(";").replace(VAR_g, ";var"); - while (BRACKETS.test(vars)) { - vars = vars.replace(BRACKETS_g, ""); - } - vars = vars.replace(VAR_TIDY, "").replace(VAR_EQUAL, ""); - } - block = decodeBlocks(block, ENCODED_BLOCK); - - // process each identifier - if (args != "_no_shrink_") { - var count = 0, shortId; - var ids = match([args, vars], IDENTIFIER); - var processed = {}; - for (var i = 0; i < ids.length; i++) { - id = ids[i]; - if (!processed["#" + id]) { - processed["#" + id] = true; - id = rescape(id); - // encode variable names - while (new RegExp(Shrinker.PREFIX + count + "\\b").test(block)) count++; - var reg = new RegExp("([^\\w$.])" + id + "([^\\w$:])"); - while (reg.test(block)) { - block = block.replace(global(reg), "$1" + Shrinker.PREFIX + count + "$2"); - } - var reg = new RegExp("([^{,\\w$.])" + id + ":", "g"); - block = block.replace(reg, "$1" + Shrinker.PREFIX + count + ":"); - count++; - } - } - total = Math.max(total, count); - } - var replacement = prefix + "~" + blocks.length + "~"; - blocks.push(block); - } else { - var replacement = "~#" + blocks.length + "~"; - blocks.push(prefix + block); - } - return replacement; - }; - - // decoder for program blocks - function decodeBlocks(script, encoded) { - while (encoded.test(script)) { - script = script.replace(global(encoded), function(match, index) { - return blocks[index]; - }); - } - return script; - }; - - // encode blocks, as we encode we replace variable and argument names - while (BLOCK.test(script)) { - script = script.replace(BLOCK_g, encodeBlocks); - } - - // put the blocks back - script = decodeBlocks(script, ENCODED_BLOCK); - - var shortId, count = 0; - var shrunk = new Encoder(Shrinker.SHRUNK, function() { - // find the next free short name - do shortId = Packer.encode52(count++); - while (new RegExp("[^\\w$.]" + shortId + "[^\\w$:]").test(script)); - return shortId; - }); - script = shrunk.encode(script); - - return this.decodeData(script); - } -}, { - ENCODED_DATA: /\x01(\d+)\x01/g, - PREFIX: "\x02", - SHRUNK: /\x02\d+\b/g -}); - -}; //////////////////// END: CLOSURE ///////////////////////////////////// diff --git a/build/scripts/nwjslint.sh b/build/scripts/nwjslint.sh deleted file mode 100755 index 69ebf4b..0000000 --- a/build/scripts/nwjslint.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/bash - -echo -ne "NW: running javascript lint on sources" - -# set sources -SOURCES=${1} -if [ "${SOURCES}x" == 'x' ]; then - pushd . &> /dev/null - cd ..; SOURCES=`pwd` - popd &> /dev/null -fi - -# check platform -PLATFORM=`uname -s` - -# set platform specifick executables -if [ $PLATFORM == 'Darwin' ]; then - JSL=bin/jsl_macos -elif [ $PLATFORM == 'Linux' ]; then - JSL=bin/jsl_linux -elif [ $PLATFORM == 'Windows' ]; then - JSL=bin/jsl.exe -fi - -# save current working path -pusdh . &> /dev/null - -# enter root path -cd $SOURCES - -> $SOURCES/dist/lint.log - -for item in `find $SOURCES/src -type d` -do { - sources=`ls $item/*.js 2>/dev/null` - for file in $sources - do { - $JSL -conf build/conf/jsl.conf -nologo -nofilelisting -nosummary -process $file >> $SOURCES/dist/lint.log - echo -ne "." - } done -} done - -echo "" - -popd &> /dev/null - -exit 0 diff --git a/build/scripts/nwpacker.js b/build/scripts/nwpacker.js deleted file mode 100755 index 006849c..0000000 --- a/build/scripts/nwpacker.js +++ /dev/null @@ -1,34 +0,0 @@ -/* - * SpiderMonkey wrapper to compress Javascript source files, - * uses Dean Edwards (http://dean.edwards.name/packer/) - * - * Author: Diego Perini - * - * Usage: fusecomp.js < input > output (uses stdin/stdout) - * - * Depends on correctly installed SpiderMonkey executable (js) - * - * Released under the Creative Commons license: - * http://creativecommons.org/licenses/by/3.0/ - */ - -// import Dean Edwards project files -load("build/packer/base2.js"); -load("build/packer/packer.js"); - -// read file from stdin -function _readFile(from) { - var outstr = '', line = ''; - while ((line = readline()) != null) { - outstr += line + '\x0a'; - } - return outstr; -} - -// read from input pack and send to output -(function minify() { - // create new packer instance - var packer = new Packer(); - // shrink! - print(packer.pack(_readFile(), 0, 1, 1)); -})(); diff --git a/build/scripts/nwpackjs.sh b/build/scripts/nwpackjs.sh deleted file mode 100755 index 83e6c6e..0000000 --- a/build/scripts/nwpackjs.sh +++ /dev/null @@ -1,72 +0,0 @@ -#!/bin/bash - -echo -ne "NW: building distribution from sources" - -# retrieve build infos -VERSION=`cat ${SOURCES}build/VERSION` -REVISION=1 - -# set used variables -BASEDIR=`pwd` -PKGNAME="nwsapi" -RELEASE=`date +%Y%m%d%H%M%S` - -# set sources -SOURCES=${1} -if [ "${SOURCES}x" == 'x' ]; then - pushd . &> /dev/null - cd ..; SOURCES=`pwd` - popd &> /dev/null -fi - -# check working platform -PLATFORM=`uname -s` - -# set platform specifick executables -if [ $PLATFORM == 'Darwin' ]; then - JSMIN=bin/jsmin_macos - JSVM=bin/js_macos -elif [ $PLATFORM == 'Linux' ]; then - JSMIN=bin/jsmin_linux - JSVM=bin/js_linux -elif [ $PLATFORM == 'Windows' ]; then - JSMIN=bin/jsmin.exe - JSVM=bin/js.exe -fi - -pushd . &> /dev/null - -cd $SOURCES - -# ensure empty -#> dist/$PKGNAME-src.js -> dist/$PKGNAME.min.js - -cat build/HEADER >> dist/$PKGNAME.min.js - -# add selector engine to source file -#cat src/nwsapi.js >> dist/$PKGNAME-src.js - -# add selector engine to minified file -cat src/nwsapi.js | $JSMIN | tr -d "\n" >> dist/$PKGNAME.min.js -echo >> dist/$PKGNAME.min.js - -# minification of variables and privates -echo "" -echo -ne "NW: starting minification, takes time please wait, " -#$JSVM build/scripts/nwpacker.js < dist/nwsapi-src.js >> dist/nwsapi-pac.js -echo -ne "complete..." -echo "" - -# build a compressed version of the minified file -#gzip -c -n9 dist/$PKGNAME-pac.js > dist/$PKGNAME-zip.js - -# build a versioned file name of the minified file -#cp dist/$PKGNAME-pac.js dist/$PKGNAME-$RELEASE.js - -# now copy packed file to the real nwsapi.js -#cp dist/nwsapi-pac.js dist/nwsapi.js - -popd &> /dev/null - -exit 0 diff --git a/build/scripts/nwtestjs.sh b/build/scripts/nwtestjs.sh deleted file mode 100755 index 378114b..0000000 --- a/build/scripts/nwtestjs.sh +++ /dev/null @@ -1,45 +0,0 @@ -#!/bin/bash - -echo -ne "NW: VM loading test, building test units..." - -# retrieve build infos -VERSION=`cat ${SOURCES}build/VERSION` -REVISION=1 - -# set used variables -BASEDIR=`pwd` -PKGNAME="nwsapi" -RELEASE=`date +%Y%m%d%H%M%S` - -# set source -SOURCES=${1} -if [ "${SOURCES}x" == 'x' ]; then - pushd . &> /dev/null - cd ..; SOURCES=`pwd` - popd &> /dev/null -fi - -# check platform -PLATFORM=`uname -s` - -if [ $PLATFORM == 'Darwin' ]; then - JS=bin/js_macos -elif [ $PLATFORM == 'Linux' ]; then - JS=bin/js_linux -elif [ $PLATFORM == 'Windows' ]; then - JS=bin/js.exe -fi - -pusdh . &> /dev/null - -$JS test/jsvm/load_test.js < test/jsvm/load_test.html - -if [ $? == '0' ]; then - echo 'PASSED' -elif [ $? != '0' ]; then - echo 'FAILED' -fi - -popd &> /dev/null - -exit 0 diff --git a/dist/lint.log b/dist/lint.log deleted file mode 100644 index e69de29..0000000 diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000..7ab8263 --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,58 @@ +import { defineConfig } from "eslint/config"; +import js from '@eslint/js'; +import globals from 'globals'; + +export default defineConfig([ + js.configs.recommended, + { + files: ['src/**/*.js', 'scripts/**/*.js', 'test_new/**/*.js'], + languageOptions: { + ecmaVersion: 'latest', + sourceType: 'script', + globals: { + ...globals.browser, + ...globals.commonjs, + ...globals.amd, + NW: 'readonly', + }, + }, + rules: { + 'no-console': 'off', + 'no-unused-vars': 'off', + 'no-cond-assign': 'off', + 'no-control-regex': 'off', + 'no-useless-escape': 'off', + 'no-redeclare': 'off', + 'no-empty': 'off', + + 'default-case': 'error', + 'no-duplicate-case': 'error', + 'radix': 'error', + 'no-with': 'error', + }, + }, + { + files: ['test/**/*.js'], + languageOptions: { + ecmaVersion: 'latest', + sourceType: 'script', + globals: { + ...globals.browser, + ...globals.commonjs, + ...globals.amd, + NW: 'readonly', + }, + }, + rules: { + 'no-console': 'off', + 'no-unused-vars': 'off', + 'no-cond-assign': 'off', + 'no-control-regex': 'off', + 'no-useless-escape': 'off', + 'no-redeclare': 'off', + 'no-empty': 'off', + 'no-undef': 'off', + radix: 'off', + }, + }, +]); diff --git a/package.json b/package.json index cf814d2..191c2de 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "nwsapi", "version": "2.2.23", "description": "Fast CSS Selectors API Engine", - "homepage": "https://javascript.nwbox.com/nwsapi/", + "homepage": "https://github.com/dperini/nwsapi/", "main": "./src/nwsapi", "keywords": [ "css", @@ -11,12 +11,6 @@ "matcher", "selector" ], - "licenses": [ - { - "type": "MIT", - "url": "https://javascript.nwbox.com/nwsapi/MIT-LICENSE" - } - ], "license": "MIT", "author": { "name": "Diego Perini", @@ -38,6 +32,18 @@ "url": "git://github.com/dperini/nwsapi.git" }, "scripts": { - "lint": "eslint ./src/nwsapi.js" + "clean": "node ./scripts/clean.mjs", + "min": "node ./scripts/min.mjs", + "lint": "npx eslint src/nwsapi.js", + "test:browser": "cross-env HARNESS_MODE=normal playwright test", + "test:browser:fixme": "cross-env HARNESS_MODE=fixme playwright test" + }, + "devDependencies": { + "@playwright/test": "^1.59.1", + "@types/node": "^25.5.2", + "cross-env": "^10.1.0", + "eslint": "9.31.0", + "playwright": "^1.59.1", + "terser": "5.46.1" } } diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 0000000..c74adf5 --- /dev/null +++ b/playwright.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from '@playwright/test'; + +export default defineConfig({ + testDir: 'test_new/browser', + testMatch: /.*\.test\.ts/, + reporter: 'list', +}); diff --git a/scripts/clean.mjs b/scripts/clean.mjs new file mode 100644 index 0000000..e0387f6 --- /dev/null +++ b/scripts/clean.mjs @@ -0,0 +1,4 @@ +import { rm } from 'node:fs/promises'; + +await rm('./dist', { recursive: true, force: true }); +console.log('removed ./dist'); diff --git a/scripts/min.mjs b/scripts/min.mjs new file mode 100644 index 0000000..cd87e91 --- /dev/null +++ b/scripts/min.mjs @@ -0,0 +1,31 @@ +import { mkdir, readFile, writeFile } from 'node:fs/promises'; +import { minify } from 'terser'; + +const pkg = JSON.parse(await readFile('./package.json', 'utf8')); +const source = await readFile('./src/nwsapi.js', 'utf8'); + +const year = new Date().getFullYear(); +const banner = [ + '/*!', + ` * NWSAPI ${pkg.version} - ${pkg.description}`, + ` * Copyright (c) 2007-${year} Diego Perini`, + ' * See https://github.com/dperini/nwsapi', + ' */', +].join('\n'); + +const result = await minify(source, { + compress: true, + mangle: true, + format: { + comments: false, + }, +}); + +if (!result.code) { + throw new Error('terser produced no output'); +} + +await mkdir('./dist', { recursive: true }); +await writeFile('./dist/nwsapi.min.js', `${banner}\n${result.code}\n`, 'utf8'); + +console.log('wrote ./dist/nwsapi.min.js'); diff --git a/src/nwsapi.js b/src/nwsapi.js index 82f9393..84909c9 100644 --- a/src/nwsapi.js +++ b/src/nwsapi.js @@ -486,7 +486,7 @@ } else nodes = none; } return !Config.NODE_LIST ? - nodes : isInstanceof(nodes) ? + nodes : isInstanceOf(nodes) ? nodes : toNodeList(nodes); }, diff --git a/test_new/README.md b/test_new/README.md new file mode 100644 index 0000000..92a86d7 --- /dev/null +++ b/test_new/README.md @@ -0,0 +1,87 @@ +# Browser harness (Playwright) + +Browser-based tests for `nwsapi`, migrated from older selector suites and run under Playwright. + +The harness compares `NW.Dom` against native DOM behavior in Chromium, Firefox, and WebKit. Tests run inside the page via `page.evaluate()`, which makes it possible to measure native browser results directly and compare them against `nwsapi` under the same fixture and context. + +## Install + +Requires Node.js (which includes npm). + +```sh +npm install +npx playwright install +``` + +`npm install` pulls in the dev dependencies needed to run the scripts. `npx playwright install` installs the browser binaries used by the harness. + +## Run + +Run the full browser harness: + +```sh +npm run test:browser +``` + +Run only cases marked `fixme`: + +```sh +npm run test:browser:fixme +``` + +Run a subset by label, for example: + +```sh +npm run test:browser jquery +npm run test:browser:fixme w3c +``` + +For faster iteration, run a subset by label or mark a scenario/case `only`. + +`fixme` cases are open questions or known mismatches found during migration and need review. + +## Tests + +Tests are written as scenario collections and run through the shared harness. + +A typical test file looks like this: + +```ts +import { runScenarios } from './harness/scenarios'; + +runScenarios('jquery', 'normal', [ + { + name: 'id selectors', + markup: `
`, + cases: [ + { select: '#a', expect: { ids: ['a'] } }, + { select: '#b', expect: { ids: ['b'] } }, + ], + }, +]); +``` + +## Scenarios + +Scenarios can: + +- choose engines (`nw`, `native`) and browsers +- provide inline HTML fixtures +- use `setupPage` to run page-side JavaScript before assertions +- use steps to change page state between groups of cases +- express cases using `select`, `first`, `match`, `closest`, `byId`, `byTag`, and `byClass` +- attach expectations such as `count`, `ids`, `classes`, `throws`, and inclusion/exclusion checks +- use context refs when a query should run relative to a specific node, including rehomed contexts for detached nodes and fragments +- mark scenarios or cases as `skip`, `only`, `fail`, or `fixme` + +## Philosophy + +The harness reduces selector tests to two things: a query and a context. + +Cases always compare `NW.Dom` against native browser behavior. Explicit expectations are extra assertions on top of that comparison. + +Contexts can also be rehomed, so the same ref can be tested in its original document, detached, or inside a `DocumentFragment`. + +## Notes + +For simple iframes, `srcdoc` is often enough. For more control, give the scenario a `url` to ground the parent page, then navigate the frame to routed HTML on the same origin. diff --git a/test_new/browser/css3-compat.test.ts b/test_new/browser/css3-compat.test.ts new file mode 100644 index 0000000..2a5452a --- /dev/null +++ b/test_new/browser/css3-compat.test.ts @@ -0,0 +1,653 @@ +import { runScenarios } from "./harness/scenarios"; + +runScenarios('css3 compat', 'normal', [ + { + name: 'test 0 basic selectors', + markup: ` +
+

CSS 3 Selectors tests

+

Original CSS work by Daniel Glazman (c) Disruptive Innovations 2008

+

Testing code written by Diego Perini. It should help improve the consistency with querySelectorAll results and match browsers internal CSS selectors behavior. Selection method calls are wrapped in a try/catch block for all libs to avoid possible errors preventing the tests to complete. Moving the mouse over the red/lime blocks will show the tooltips with info on the tests.

+
+ +
+
+
+ +
+
+
+ + `, + setupPage: async (page) => { await page.evaluate(() => { location.hash = 'target'; });}, + cases: [ + /* element type selector */ + { select: 'body', expect: { count: 1 } }, + { select: 'div', expect: { count: 6 } }, + { select: 'div.header', expect: { count: 1 } }, + { select: 'div.footer', expect: { count: 1 } }, + { select: 'h3, h4, p, ul', expect: { count: 5 } }, + + /* class selector */ + { select: '.unitTest', expect: { count: 2 } }, + { select: '.test', expect: { count: 2 } }, + + /* group of selectors */ + { select: '.unitTest, .test', expect: { count: 4 } }, + + /* :target selector */ + { select: '.target :target', expect: { count: 1 } }, + ], + }, + { + name: 'test 1 childhood selector', + markupMode: 'html-document', + markup: ` + + + +
+
+
+ + + `, + cases: [ + /* test 1 : childhood selector */ + { select: 'html > body', expect: { count: 1 } }, + { select: '.test > .blox1', expect: { count: 1 } }, + ], + }, + { + name: 'test 2 attribute existence selector', + markup: ` +
+
+
+
+
+
+ `, + cases: [ + /* attribute with a value */ + { select: '.blox2[align]', expect: { count: 1 } }, + + /* attribute with empty value */ + { select: '.blox3[align]', expect: { count: 1 } }, + + /* attribute with almost similar name */ + { select: '.blox4, .blox5', expect: { count: 2 } }, + { select: '.blox4[align], .blox5[align]', expect: { count: 0 } }, + ], + }, + { + name: 'test 3 attribute value selector', + markup: ` +
+
+
+
+
+ `, + cases: [ + /* test 3 : attribute value selector */ + { select: '.blox6[align="center"]', expect: { count: 1 } }, + { select: '.blox6[align="c"]', expect: { count: 0 } }, + { select: '.blox6[align="centera"]', expect: { count: 0 } }, + { select: '.blox6[foo="\\e9"]', expect: { count: 1 } }, + { select: '.blox6[\\_foo="\\e9"]', expect: { count: 1 } }, + ], + }, + { + name: 'test 4 space-separated attribute selector', + markup: ` +
+
+
+
+
+
+ `, + cases: [ + /* test 4 : [~=] */ + { select: '.blox7[class~="foo"]', expect: { count: 1 } }, + { select: '.blox8, .blox9, .blox10', expect: { count: 3 } }, + { select: '.blox8[class~=""]', expect: { count: 0 } }, + { select: '.blox9[foo~=""]', expect: { count: 0 } }, + { select: '.blox10[foo~="foo"]', expect: { count: 0 } }, + ], + }, + { + name: 'test 5 attribute starts-with selector', + markup: ` +
+
+
+
+
+
+ `, + cases: [ + /* test5 [^=] */ + { select: '.attrStart > .t3', expect: { count: 1 } }, + { select: '.attrStart > .t1[class^="unit"]', expect: { count: 1 } }, + { select: '.attrStart > .t2', expect: { count: 1 } }, + { select: '.attrStart > .t2[class^="nit"]', expect: { count: 0 } }, + { select: '.attrStart > .t3[align^=""]', expect: { count: 0 } }, + { select: '.attrStart > .t4[foo^="\\e9"]', expect: { count: 1 } }, + ], + }, + { + name: 'test 6 attribute ends-with selector', + markup: ` +
+
+
+
+
+
+ `, + cases: [ + /* test6 [$=] */ + { select: '.attrEnd > .t3', expect: { count: 1 } }, + { select: '.attrEnd > .t1[class$="t1"]', expect: { count: 1 } }, + { select: '.attrEnd > .t2', expect: { count: 1 } }, + { select: '.attrEnd > .t2[class$="unit"]', expect: { count: 0 } }, + { select: '.attrEnd > .t3[align$=""]', expect: { count: 0 } }, + { select: '.attrEnd > .t4[foo$="\\e9"]', expect: { count: 1 } }, + ], + }, + { + name: 'test 7 attribute contains selector', + markup: ` +
+
+
+
+
+
+ `, + cases: [ + /* test7 [*=] */ + { select: '.attrMiddle > .t3', expect: { count: 1 } }, + { select: '.attrMiddle > .t1[class*="t t"]', expect: { count: 1 } }, + { select: '.attrMiddle > .t2', expect: { count: 1 } }, + { select: '.attrMiddle > .t2[class*="a"]', expect: { count: 0 } }, + { select: '.attrMiddle > .t3[align*=""]', expect: { count: 0 } }, + { select: '.attrMiddle > .t4[foo*="\\e9"]', expect: { count: 1 } }, + ], + }, + { + name: 'first-child selector', + markup: ` +
+
+
+
+
+ `, + cases: [ + /* :first-child tests */ + { select: '.firstChild .unitTest:first-child', expect: { count: 1 } }, + { select: '.blox12:first-child', expect: { count: 0 } }, + { select: '.blox13:first-child', expect: { count: 0 } }, + { select: '.blox12, .blox13', expect: { count: 2 } }, + ], + }, + { + name: 'root selector', + markup: '', + cases: [ + /* :root tests */ + { select: 'html', expect: { equivalentCase: { select: ':root' } } }, + ], + }, + { + name: ':nth-child(n) and :nth-of-type tests', + markup: ` +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+

+

+
+

+
+
+
+
+
+

+

+
+

+
+
+
+
+
+

+

+
+

+
+
+

+
+
+
+ `, + cases: [ + /* :nth-child(n) tests */ + { select: '.nthchild1 > :nth-last-child(odd)', expect: { count: 3 } }, + { select: '.nthchild1 > :nth-child(odd)', expect: { count: 3 } }, + + { select: '.nthchild2 > :nth-last-child(even)', expect: { count: 3 } }, + { select: '.nthchild2 > :nth-child(even)', expect: { count: 3 } }, + + { select: '.nthchild3 > :nth-child(3n+2)', expect: { count: 2 } }, + { select: '.nthchild3 > :nth-last-child(3n+1)', expect: { count: 2 } }, + { select: '.nthchild3 > :nth-last-child(3n+3)', expect: { count: 2 } }, + + { select: '.nthoftype1 > div:nth-of-type(odd)', expect: { count: 2 } }, + { select: '.nthoftype1 > div:nth-last-of-type(odd)', expect: { count: 2 } }, + { select: '.nthoftype1 > p', expect: { count: 3 } }, + + { select: '.nthoftype2 > div:nth-of-type(even)', expect: { count: 2 } }, + { select: '.nthoftype2 > div:nth-last-of-type(even)', expect: { count: 2 } }, + { select: '.nthoftype2 > p', expect: { count: 3 } }, + + { select: '.nthoftype3 > div:nth-of-type(3n+1)', expect: { count: 2 } }, + { select: '.nthoftype3 > div:nth-last-of-type(3n+1)', expect: { count: 2 } }, + { select: '.nthoftype3 > div:nth-last-of-type(3n+2)', expect: { count: 2 } }, + { select: '.nthoftype3 > p', expect: { count: 4 } }, + ], + }, + { + name: 'not pseudo-class selector', + markup: ` +
+
+
+
+
+ `, + cases: [ + /* :not() tests */ + { select: '.blox14:not(span)', expect: { count: 1 } }, + { select: '.blox15:not([foo="blox14"])', expect: { count: 1 } }, + { select: '.blox16', expect: { count: 1 } }, + { select: '.blox16:not(.blox15)', expect: { count: 1 } }, + { select: '.blox16:not(.blox15[foo="blox14"])', expect: { count: 1 } }, + { select: '.unitTest:not(.blox15[foo="blox15"])', expect: { count: 2 } }, + ], + }, + { + name: ':only-of-type tests', + markup: ` +
+
+

+

+
+ `, + cases: [ + /* :only-of-type tests */ + { select: '.blox17', expect: { count: 1 } }, + { select: '.blox17:only-of-type', expect: { count: 1 } }, + { select: '.blox18:only-of-type', expect: { count: 0 } }, + { select: '.blox18:not(:only-of-type)', expect: { count: 2 } }, + ], + }, + { + name: ':last-child tests', + markup: ` +
+

+
  +
+ `, + cases: [ + /* :last-child tests */ + { select: '.lastChild > p', expect: { count: 1 } }, + { select: '.lastChild > :last-child', expect: { count: 1 } }, + { select: '.lastChild > :not(:last-child)', expect: { count: 1 } }, + ], + }, + { + name: ':first-of-type tests', + markup: ` +
+

+
+

+
+
+ `, + cases: [ + /* :first-of-type tests */ + { select: '.firstOfType > p', expect: { count: 2 } }, + { select: '.firstOfType > *:first-of-type', expect: { count: 2 } }, + { select: '*.firstOfType > :not(:first-of-type)', expect: { count: 2 } }, + ], + }, + + + { + name: ':last-of-type tests', + markup: ` +
+

+
+

+
+
+ `, + cases: [ + /* :last-of-type tests */ + { select: '.lastOfType > p', expect: { count: 2 } }, + { select: '.lastOfType > *:last-of-type', expect: { count: 2 } }, + { select: '*.lastOfType > :not(:last-of-type)', expect: { count: 2 } }, + ], + }, + { + name: ':only-child tests', + markup: ` +
+
+
+
+
+
+ `, + cases: [ + /* :only-child tests */ + { select: '.onlyChild > *:not(:only-child)', expect: { count: 2 } }, + { select: '.onlyChild > .unitTest > *:only-child', expect: { count: 1 } }, + ], + }, + { + name: ':only-of-type tests 2', + markup: ` +
+

+
+
+
+
+
+ `, + cases: [ + /* :only-of-type tests */ + { select: '.onlyOfType *:only-of-type', expect: { count: 2 } }, + { select: '.onlyOfType *:not(:only-of-type)', expect: { count: 2 } }, + ], + }, + + { + name: ':empty tests', + markup: ` +
+
+
+
+
+
 
+
+ `, + cases: [ + /* :empty tests */ + { select: '.empty > .isEmpty', expect: { count: 2 } }, + { select: '.empty > *.isEmpty:empty', expect: { count: 2 } }, + { select: '.empty > .isNotEmpty', expect: { count: 3 } }, + { select: '.empty > .isNotEmpty:empty', expect: { count: 0 } }, + { select: '.empty > .isNotEmpty:not(:empty)', expect: { count: 3 } }, + ], + }, + { + name: ':lang() tests', + markup: ` +
+
+
+
+
+
+ `, + setupPage: async (page) => { + await page.evaluate(() => { + document.documentElement.lang = 'en'; + }); + }, + cases: [ + /* :lang() tests */ + { select: '.lang :lang(en)', expect: { count: 2 } }, + { select: '.lang :lang(fr)', expect: { count: 1 } }, + { select: '.lang .t1', expect: { count: 1 } }, + { select: '.lang .t1:lang(es)', expect: { count: 1 } }, + { select: '.lang :lang(es-AR)', expect: { count: 0 } }, + ], + }, + { + name: '[|=] tests', + markup: ` +
+
+
+
+
+
+ `, + setupPage: async (page) => { + await page.evaluate(() => { + document.documentElement.lang = 'en'; + }); + }, + cases: [ + /* [|=] tests */ + { select: '.attrLang .t1', expect: { count: 1 } }, + { select: '.attrLang .t1[lang|="en"]', expect: { count: 0 } }, + { select: '.attrLang [lang|="fr"]', expect: { count: 1 } }, + { select: '.attrLang .t2[lang|="en"]', expect: { count: 1 } }, + { select: '.attrLang .t3', expect: { count: 1 } }, + { select: '.attrLang .t3[lang|="es"]', expect: { count: 1 } }, + { select: '.attrLang [lang|="es-AR"]', expect: { count: 0 } }, + ], + }, + + { + name: 'UI tests', + markup: ` +
+ + +
+
+
+ the previous square should be green when the checkbox is checked and become red when you uncheck it +
+
+
+ the previous square should be green when the checkbox is NOT checked and become red when you check it +
+ `, + cases: [ + /* UI tests */ + { select: '.UI', expect: { count: 3 } }, + { select: '.UI > *', expect: { count: 6 } }, + { select: '.UI .t1:enabled > .unitTest', expect: { count: 1 } }, + { select: '.UI .t2:disabled > .unitTest', expect: { count: 1 } }, + { select: '.UI .t3:checked + div', expect: { count: 1 } }, + { select: '.UI .t4:not(:checked) + div', expect: { count: 1 } }, + ], + }, + { + name: '~ combinator tests', + markup: ` +
+
+
+
+
+ the three last squares should be green and become red when the pointer hovers over the white square +
+ `, + steps: [ + { + // ensure baseline starts non-hovered; native :hover may already match if the pointer begins over the target + setupPage: async (page) => { await page.mouse.move(200, 200); }, + cases: [ + /* ~ combinator tests */ + { select: '.tilda', expect: { count: 1 } }, + { select: '.tilda .t1', expect: { count: 1 } }, + { select: '.tilda .t1 ~ .unitTest', expect: { count: 3 } }, + { select: '.tilda .t1:hover ~ .unitTest', expect: { count: 0 } }, + ], + }, + { + setupPage: async (page) => { await page.locator('.tilda .t1').hover(); }, + cases: [ + { select: '.tilda .t1:hover', expect: { count: 1 } }, + { select: '.tilda .t1:hover ~ .unitTest', expect: { count: 3 } }, + ], + }, + ], + }, + { + name: '+ combinator tests', + markup: ` +
+
+
+
+ the last square should be green and become red when the pointer hovers over the FIRST white square +
+ `, + steps: [ + { + // ensure baseline starts non-hovered; + setupPage: async (page) => { await page.mouse.move(200, 200); }, + cases: [ + /* + combinator tests */ + { select: '.plus', expect: { count: 1 } }, + { select: '.plus .t1, .plus .t2', expect: { count: 2 } }, + { select: '.plus .t1 + .unitTest + .unitTest', expect: { count: 1 } }, + { select: '.plus .t1:hover + .unitTest + .unitTest', expect: { count: 0 } }, + ], + }, + { + setupPage: async (page) => { await page.locator('.plus .t1').hover(); }, + cases: [ + { select: '.plus .t1:hover + .unitTest + .unitTest', expect: { count: 1 } }, + ], + }, + ], + }, + { + name: 'attribute case sensitivity identifier tests', + markup: ` +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ `, + cases: [ + { select: '.blox23s1[foo="blox" i]', expect: { count: 1 } }, + { select: '.blox23s2[foo="blox" i]', expect: { count: 1 } }, + { select: '.blox23s3[foo="blox" i]', expect: { count: 1 } }, + { select: '.blox23s4[foo="blox" i]', expect: { count: 1 } }, + { select: '.blox23s5[foo="blox" i]', expect: { count: 1 } }, + { select: '.blox23s6[foo="blox" i]', expect: { count: 1 } }, + { select: '.blox23s1[foo="blox" erroneous]', expect: { throws: true } }, + { select: '.blox19[class="BLOX19 UNITTEST" i]', expect: { count: 1 } }, + { select: '.blox20[class="BLOX20 UNITTEST" i]', expect: { count: 1 } }, + { select: '.blox20[class="blox20 unitTest" s]', status: 'fixme' }, + { select: '.blox21[class*="21 UN" i]', expect: { count: 1 } }, + { select: '.blox22[class*="22 unitt" s]', status: 'fixme' }, + { select: '.blox22[class*="22 unitT" s]', status: 'fixme' }, + { select: '.blox24[class^="BLOX" i]', expect: { count: 1 } }, + { select: '.blox25[class^="BLOX"]', expect: { count: 0 } }, + { select: '.blox25[class^="blox" s]', status: 'fixme' }, + { select: '.blox26[class$="tEST" i]', expect: { count: 1 } }, + { select: '.blox27[class$="TEst" s]', status: 'fixme' }, + { select: '.blox27[class$="Test" s]', status: 'fixme' }, + { select: '.blox28[class~="unitTEST" i]', expect: { count: 1 } }, + ], + }, + { + name: 'attribute s-flag divergence', + status: 'fail', + markup: ` +
+
+
+
+
+
+ `, + cases: [ + { select: '.blox20[class="blox20 unitTest" s]' }, + { select: '.blox22[class*="22 unitt" s]' }, + { select: '.blox22[class*="22 unitT" s]' }, + { select: '.blox25[class^="blox" s]' }, + { select: '.blox27[class$="TEst" s]' }, + { select: '.blox27[class$="Test" s]' }, + ], + }, + { + name: 'double-negation not selector', + markup: `
`, + cases: [ + { select: 'div:not(:not(div))', expect: { ids: ['a'] } }, + ], + }, +]); diff --git a/test_new/browser/css3-escape.test.ts b/test_new/browser/css3-escape.test.ts new file mode 100644 index 0000000..962d0e0 --- /dev/null +++ b/test_new/browser/css3-escape.test.ts @@ -0,0 +1,412 @@ +import { type Page } from "@playwright/test"; +import { runScenarios } from "./harness/scenarios"; + +const setupNw = async (page: Page) => { + await page.evaluate(() => { + NW.Dom.configure({ + SELECTOR3: true, + NON_ASCII: true, + UNICODE16: true, + ESCAPECHR: true, + VERBOSITY: false, + }); + }); +} + +runScenarios('css3 escaped identifiers', 'normal', [ + { + name: 'non-escaped identifier', + markup: `
`, + setupPage: setupNw, + cases: [ + // 4.3.7 from https://www.w3.org/TR/css-syntax-3/#consume-an-escaped-code-point + { select: '#nonescaped', expect: { count: 1 } }, + { select: '.nonescaped', expect: { count: 1 } }, + ], + }, + { + name: 'escape hex digit identifier', + markup: ` +
+ + + + +
`, + setupPage: setupNw, + cases: [ + // - escape hex digit + { select: '#\\30 nextIsWhiteSpace', expect: { count: 1 } }, + { select: '.\\30 nextIsWhiteSpace', expect: { count: 1 } }, + + { select: '#\\30nextIsNotHexLetters', expect: { count: 1 } }, + { select: '.\\30nextIsNotHexLetters', expect: { count: 1 } }, + + { select: '#\\000030connectHexMoreThan6Hex', expect: { count: 1 } }, + { select: '.\\000030connectHexMoreThan6Hex', expect: { count: 1 } }, + + { select: '#\\000030 spaceMoreThan6Hex', expect: { count: 1 } }, + { select: '.\\000030 spaceMoreThan6Hex', expect: { count: 1 } }, + ], + }, + // { + // // - hex digit special replacement + // } + { + name: 'zero points', + markup: '', // set up page in setupPage callback to avoid issues with unrepresentable characters in HTML source + // html: ` + //
+ // + // + // + // + //
`, + setupPage: async (page) => { + setupNw(page); + await page.evaluate(() => { + document.body.innerHTML = ''; + const root = document.createElement('div'); + + const one = document.createElement('span'); + one.id = one.className = 'one\uFFFD'; + + const two = document.createElement('span'); + two.id = two.className = 'two\u0000'; + + const three = document.createElement('span'); + three.id =three.className = 'three\uFFFD'; + + const four = document.createElement('span'); + four.id = four.className = 'four\u0000'; + + root.append(one, two, three, four); + document.body.appendChild(root); + }); + }, + cases: [ + // 1. zero points + { select: '#one\\0', expect: { count: 1 } }, + { select: '.one\\0', expect: { count: 1 } }, + + { select: '#two\\0', expect: { count: 0 } }, + { select: '.two\\0', expect: { count: 0 } }, + + { select: '#three\\000000', expect: { count: 1 } }, + { select: '.three\\000000', expect: { count: 1 } }, + + { select: '#four\\000000', expect: { count: 0 } }, + { select: '.four\\000000', expect: { count: 0 } }, + ], + }, + { + name: 'surrogate points', + markup: ` +
+ + + + + + + + +
`, + setupPage: setupNw, + cases: [ + // 2. surrogate points + { select: '#\\d83d surrogateFirstA', expect: { count: 1, ids: ['\u{fffd}surrogateFirstA'] } }, + { select: '.\\d83d surrogateFirstA', expect: { count: 1, ids: ['\u{fffd}surrogateFirstA'] } }, + { select: '#\\d83d surrogateFirstB', expect: { count: 0 } }, + { select: '.\\d83d surrogateFirstB', expect: { count: 0 } }, + + { select: '#surrogateSecondC\\dd11', expect: { count: 1, ids: ['surrogateSecondC\u{fffd}'] } }, + { select: '.surrogateSecondC\\dd11', expect: { count: 1, ids: ['surrogateSecondC\u{fffd}'] } }, + { select: '#surrogateSecondD\\dd11', expect: { count: 0 } }, + { select: '.surrogateSecondD\\dd11', expect: { count: 0 } }, + + { select: '#surrogatePairE\\d83d\\dd11', expect: { count: 1, ids: ['surrogatePairE\u{fffd}\u{fffd}'] } }, + { select: '.surrogatePairE\\d83d\\dd11', expect: { count: 1, ids: ['surrogatePairE\u{fffd}\u{fffd}'] } }, + { select: '#surrogatePairF\\d83d\\dd11', expect: { count: 0 } }, + { select: '.surrogatePairF\\d83d\\dd11', expect: { count: 0 } }, + ], + }, + { + name: 'out of range points', + markup: ` +
+ + +
`, + setupPage: setupNw, + cases: [ + // 3. out of range points + { select: '#outOfRangeA\\110000', expect: { count: 1, ids: ['outOfRangeA\u{fffd}'] } }, + { select: '.outOfRangeA\\110000', expect: { count: 1, ids: ['outOfRangeA\u{fffd}'] } }, + + { select: '#outOfRangeA\\110030', expect: { count: 1, ids: ['outOfRangeA\u{fffd}'] } }, + { select: '.outOfRangeA\\110030', expect: { count: 1, ids: ['outOfRangeA\u{fffd}'] } }, + + { select: '#outOfRangeB\\110030', expect: { count: 0 } }, + { select: '.outOfRangeB\\110030', expect: { count: 0 } }, + + { select: '#outOfRangeA\\555555', expect: { count: 1, ids: ['outOfRangeA\u{fffd}'] } }, + { select: '.outOfRangeA\\555555', expect: { count: 1, ids: ['outOfRangeA\u{fffd}'] } }, + + { select: '#outOfRangeA\\ffffff', expect: { count: 1, ids: ['outOfRangeA\u{fffd}'] } }, + { select: '.outOfRangeA\\ffffff', expect: { count: 1, ids: ['outOfRangeA\u{fffd}'] } }, + ], + }, + { + name: 'escape eof', + markup: ` +
+ + +
`, + setupPage: setupNw, + cases: [ + // trailing backslash escapes EOF -> U+FFFD + { select: '#eofA\\', expect: { count: 1, ids: ['eofA\u{fffd}'] } }, + { select: '.eofA\\', expect: { count: 1, ids: ['eofA\u{fffd}'] } }, + + { select: '#eofB\\', expect: { count: 0 } }, + { select: '.eofB\\', expect: { count: 0 } }, + ], + }, + { + name: 'escape anything else', + markup: ` +
+ + + +
`, + setupPage: setupNw, + cases: [ + { select: '#\\.comma', expect: { count: 1, ids: ['.comma'] } }, + { select: '.\\.comma', expect: { count: 1, ids: ['.comma'] } }, + + { select: '#\\-minus', expect: { count: 1, ids: ['-minus'] } }, + { select: '.\\-minus', expect: { count: 1, ids: ['-minus'] } }, + + { select: '#\\g', expect: { count: 1, ids: ['g'] } }, + { select: '.\\g', expect: { count: 1, ids: ['g'] } }, + ], + }, + { + name: 'non edge cases', + markup: ` +
+ + + + + + + + + + +
`, + setupPage: setupNw, + cases: [ + { select: '#\\61 BMPRegular', expect: { count: 1, ids: ['aBMPRegular'] } }, + { select: '.\\61 BMPRegular', expect: { count: 1, ids: ['aBMPRegular'] } }, + + { select: '#\\1f511 nonBMP', expect: { count: 1, ids: ['\u{1f511}nonBMP'] } }, + { select: '.\\1f511 nonBMP', expect: { count: 1, ids: ['\u{1f511}nonBMP'] } }, + + { select: '#\\30\\30 continueEscapesA', expect: { count: 1, ids: ['00continueEscapesA'] } }, + { select: '.\\30\\30 continueEscapesA', expect: { count: 1, ids: ['00continueEscapesA'] } }, + + { select: '#\\30 \\30 continueEscapesB', expect: { count: 1, ids: ['00continueEscapesB'] } }, + { select: '.\\30 \\30 continueEscapesB', expect: { count: 1, ids: ['00continueEscapesB'] } }, + + { select: '#continueEscapesC\\30 \\30 ', expect: { count: 1, ids: ['continueEscapesC00'] } }, + { select: '.continueEscapesC\\30 \\30 ', expect: { count: 1, ids: ['continueEscapesC00'] } }, + + { select: '#continueEscapesD\\30 \\30', expect: { count: 1, ids: ['continueEscapesD00'] } }, + { select: '.continueEscapesD\\30 \\30', expect: { count: 1, ids: ['continueEscapesD00'] } }, + + { select: '#continueEscapesE\\30\\30 ', expect: { count: 1, ids: ['continueEscapesE00'] } }, + { select: '.continueEscapesE\\30\\30 ', expect: { count: 1, ids: ['continueEscapesE00'] } }, + + { select: '#continueEscapesF\\30\\30', expect: { count: 1, ids: ['continueEscapesF00'] } }, + { select: '.continueEscapesF\\30\\30', expect: { count: 1, ids: ['continueEscapesF00'] } }, + ], + }, + + { + name: 'chromium ident cases 1', + markup: ` +
+ + + + + + + + + + + + + + + + + + + + +
`, + setupPage: setupNw, + cases: [ + // ident tests case from CSS tests of chromium source: https://goo.gl/3Cxdov + { select: '#hel\\6CoA', expect: { count: 1, ids: ['helloA'] } }, + { select: '.hel\\6CoA', expect: { count: 1, ids: ['helloA'] } }, + + { select: '#hel\\6C oB', expect: { count: 1, ids: ['helloB'] } }, + { select: '.hel\\6C oB', expect: { count: 1, ids: ['helloB'] } }, + + { select: '#\\26 B', expect: { count: 1, ids: ['&B'] } }, + { select: '.\\26 B', expect: { count: 1, ids: ['&B'] } }, + + { select: '#spac\\65\r\nsA', expect: { count: 1, ids: ['spacesA'] } }, + { select: '.spac\\65\r\nsA', expect: { count: 1, ids: ['spacesA'] } }, + + { select: '#sp\\61\tc\\65\fsB', expect: { count: 1, ids: ['spacesB'] } }, + { select: '.sp\\61\tc\\65\fsB', expect: { count: 1, ids: ['spacesB'] } }, + + { select: '#\\E000', expect: { count: 1, ids: ['\u{E000}'] } }, + { select: '.\\E000', expect: { count: 1, ids: ['\u{E000}'] } }, + + { select: '#testA\\D799', expect: { count: 1, ids: ['testA\u{D799}'] } }, + { select: '.testA\\D799', expect: { count: 1, ids: ['testA\u{D799}'] } }, + + { select: '#te\\s\\tB', expect: { count: 1, ids: ['testB'] } }, + { select: '.te\\s\\tB', expect: { count: 1, ids: ['testB'] } }, + + { select: '#\\.\\,\\:\\!', expect: { count: 1, ids: ['.,:!'] } }, + { select: '.\\.\\,\\:\\!', expect: { count: 1, ids: ['.,:!'] } }, + + { select: '#nullA\\0', expect: { count: 1, ids: ['nullA\u{fffd}'] } }, + { select: '.nullA\\0', expect: { count: 1, ids: ['nullA\u{fffd}'] } }, + + { select: '#nullB\\0000', expect: { count: 1, ids: ['nullB\u{fffd}'] } }, + { select: '.nullB\\0000', expect: { count: 1, ids: ['nullB\u{fffd}'] } }, + + { select: '#largeA\\110000', expect: { count: 1, ids: ['largeA\u{fffd}'] } }, + { select: '.largeA\\110000', expect: { count: 1, ids: ['largeA\u{fffd}'] } }, + + { select: '#largeB\\23456a', expect: { count: 1, ids: ['largeB\u{fffd}'] } }, + { select: '.largeB\\23456a', expect: { count: 1, ids: ['largeB\u{fffd}'] } }, + + { select: '#surrogateA\\D800', expect: { count: 1, ids: ['surrogateA\u{fffd}'] } }, + { select: '.surrogateA\\D800', expect: { count: 1, ids: ['surrogateA\u{fffd}'] } }, + + { select: '#surrogateB\\0DBAC', expect: { count: 1, ids: ['surrogateB\u{fffd}'] } }, + { select: '.surrogateB\\0DBAC', expect: { count: 1, ids: ['surrogateB\u{fffd}'] } }, + + { select: '#\\00DFFFsurrogateC', expect: { count: 1, ids: ['\u{fffd}surrogateC'] } }, + { select: '.\\00DFFFsurrogateC', expect: { count: 1, ids: ['\u{fffd}surrogateC'] } }, + + { select: '#\\10fFfF', expect: { count: 1, ids: ['\u{10ffff}'] } }, + { select: '.\\10fFfF', expect: { count: 1, ids: ['\u{10ffff}'] } }, + + { select: '#\\10fFfF0', expect: { count: 1, ids: ['\u{10ffff}0'] } }, + { select: '.\\10fFfF0', expect: { count: 1, ids: ['\u{10ffff}0'] } }, + + { select: '#\\10000000', expect: { count: 1, ids: ['\u{100000}00'] } }, + { select: '.\\10000000', expect: { count: 1, ids: ['\u{100000}00'] } }, + ], + }, + { + name: 'chromium ident cases 2', + markup: ` +
+ + + + + + + + + + + + + + + +
`, + setupPage: setupNw, + cases: [ + // ident tests case from CSS tests of chromium source: https://goo.gl/3Cxdov + { select: '#simple-ident', expect: { count: 1, ids: ['simple-ident'] } }, + { select: '.simple-ident', expect: { count: 1, ids: ['simple-ident'] } }, + + { select: '#testing123', expect: { count: 1, ids: ['testing123'] } }, + { select: '.testing123', expect: { count: 1, ids: ['testing123'] } }, + + { select: '#_underscore', expect: { count: 1, ids: ['_underscore'] } }, + { select: '._underscore', expect: { count: 1, ids: ['_underscore'] } }, + + { select: '#-text', expect: { count: 1, ids: ['-text'] } }, + { select: '.-text', expect: { count: 1, ids: ['-text'] } }, + + { select: '#-\\6d', expect: { count: 1, ids: ['-m'] } }, + { select: '.-\\6d', expect: { count: 1, ids: ['-m'] } }, + + { select: '#--abc', expect: { count: 1, ids: ['--abc'] } }, + { select: '.--abc', expect: { count: 1, ids: ['--abc'] } }, + + { select: '#--', expect: { count: 1, ids: ['--'] } }, + { select: '.--', expect: { count: 1, ids: ['--'] } }, + + { select: '#--11', expect: { count: 1, ids: ['--11'] } }, + { select: '.--11', expect: { count: 1, ids: ['--11'] } }, + + { select: '#---', expect: { count: 1, ids: ['---'] } }, + { select: '.---', expect: { count: 1, ids: ['---'] } }, + + { select: '#\u{2003}', expect: { count: 1, ids: ['\u{2003}'] } }, + { select: '.\u{2003}', expect: { count: 1, ids: ['\u{2003}'] } }, + + { select: '#\u{A0}', expect: { count: 1, ids: ['\u{A0}'] } }, + { select: '.\u{A0}', expect: { count: 1, ids: ['\u{A0}'] } }, + + { select: '#\u{1234}', expect: { count: 1, ids: ['\u{1234}'] } }, + { select: '.\u{1234}', expect: { count: 1, ids: ['\u{1234}'] } }, + + { select: '#\u{12345}', expect: { count: 1, ids: ['\u{12345}'] } }, + { select: '.\u{12345}', expect: { count: 1, ids: ['\u{12345}'] } }, + + { select: '#\u{0}', expect: { count: 1, ids: ['\u{fffd}'] }, status: 'fixme' }, + { select: '.\u{0}', expect: { count: 1, ids: ['\u{fffd}'] } }, + + { select: '#ab\u{0}c', expect: { count: 1, ids: ['ab\u{fffd}c'] } }, + { select: '.ab\u{0}c', expect: { count: 1, ids: ['ab\u{fffd}c'] } }, + ], + }, + { + name: 'spaces in ident id selector', + markup: `
`, + setupPage: setupNw, + cases: [ + { select: '#spaces\\ in\\\tident', expect: { count: 1, ids: ['spaces in\tident'] } }, + ], + }, + { + name: 'spaces in ident class selector mismatch', + status: 'fail', + markup: `
`, + setupPage: setupNw, + cases: [ + { select: '.spaces\\ in\\\tident', expect: { count: 1, ids: ['spaces in\tident'] } }, + ], + }, +]); \ No newline at end of file diff --git a/test_new/browser/fixtures/slick/MooTools_Logo.svg b/test_new/browser/fixtures/slick/MooTools_Logo.svg new file mode 100644 index 0000000..b899874 --- /dev/null +++ b/test_new/browser/fixtures/slick/MooTools_Logo.svg @@ -0,0 +1,24 @@ + + + diff --git a/test_new/browser/fixtures/slick/first-letter.gif b/test_new/browser/fixtures/slick/first-letter.gif new file mode 100644 index 0000000..04613d5 Binary files /dev/null and b/test_new/browser/fixtures/slick/first-letter.gif differ diff --git a/test_new/browser/fixtures/slick/first-letter2.gif b/test_new/browser/fixtures/slick/first-letter2.gif new file mode 100644 index 0000000..3c0a8f3 Binary files /dev/null and b/test_new/browser/fixtures/slick/first-letter2.gif differ diff --git a/test_new/browser/fixtures/slick/initial-cap.png b/test_new/browser/fixtures/slick/initial-cap.png new file mode 100644 index 0000000..ddeed89 Binary files /dev/null and b/test_new/browser/fixtures/slick/initial-cap.png differ diff --git a/test_new/browser/fixtures/slick/quirks.html b/test_new/browser/fixtures/slick/quirks.html new file mode 100644 index 0000000..81304df --- /dev/null +++ b/test_new/browser/fixtures/slick/quirks.html @@ -0,0 +1,19 @@ + + + +quirks test + + + +
+
+
+
+ + \ No newline at end of file diff --git a/test_new/browser/fixtures/slick/template-almost.html b/test_new/browser/fixtures/slick/template-almost.html new file mode 100644 index 0000000..7fe1c76 --- /dev/null +++ b/test_new/browser/fixtures/slick/template-almost.html @@ -0,0 +1,2932 @@ + + + + + + + + template xhtml as html + + + +
+

W3C + +

Selectors

+ +

W3C Working Draft 15 December 2005

+ +
+ +
This version: + +
+ http://www.w3.org/TR/2005/WD-css3-selectors-20051215 + +
Latest version: + +
+ http://www.w3.org/TR/css3-selectors + +
Previous version: + +
+ http://www.w3.org/TR/2001/CR-css3-selectors-20011113 + +
Editors: + +
Daniel Glazman (Invited Expert)
+ +
Tantek Çelik (Invited Expert) + +
Ian Hickson (Google) + +
Peter Linss (former editor, Netscape/AOL) + +
John Williams (former editor, Quark, Inc.) + +
+ +
+ +
+ +

Abstract

+ +

Selectors are patterns that match against elements in a + tree. Selectors have been optimized for use with HTML and XML, and + are designed to be usable in performance-critical code.

+ +

CSS (Cascading + Style Sheets) is a language for describing the rendering of HTML and XML documents on + screen, on paper, in speech, etc. CSS uses Selectors for binding + style properties to elements in the document. This document + describes extensions to the selectors defined in CSS level 2. These + extended selectors will be used by CSS level 3. + +

Selectors define the following function:

+ +
expression ∗ element → boolean
+ +

That is, given an element and a selector, this specification + defines whether that element matches the selector.

+ +

These expressions can also be used, for instance, to select a set + of elements, or a single element from a set of elements, by + evaluating the expression across all the elements in a + subtree. STTS (Simple Tree Transformation Sheets), a + language for transforming XML trees, uses this mechanism. [STTS]

+ +

Status of this document

+ +

This section describes the status of this document at the + time of its publication. Other documents may supersede this + document. A list of current W3C publications and the latest revision + of this technical report can be found in the W3C technical reports index at + http://www.w3.org/TR/.

+ +

This document describes the selectors that already exist in CSS1 and CSS2, and + also proposes new selectors for CSS3 and other languages that may need them.

+ +

The CSS Working Group doesn't expect that all implementations of + CSS3 will have to implement all selectors. Instead, there will + probably be a small number of variants of CSS3, called profiles. For + example, it may be that only a profile for interactive user agents + will include all of the selectors.

+ +

This specification is a last call working draft for the the CSS Working Group + (Style Activity). This + document is a revision of the Candidate + Recommendation dated 2001 November 13, and has incorporated + implementation feedback received in the past few years. It is + expected that this last call will proceed straight to Proposed + Recommendation stage since it is believed that interoperability will + be demonstrable.

+ +

All persons are encouraged to review and implement this + specification and return comments to the (archived) + public mailing list www-style + (see instructions). W3C + Members can also send comments directly to the CSS Working + Group. + The deadline for comments is 14 January 2006.

+ +

This is still a draft document and may be updated, replaced, or + obsoleted by other documents at any time. It is inappropriate to + cite a W3C Working Draft as other than "work in progress". + +

This document may be available in translation. + The English version of this specification is the only normative + version. + +

+ +

Table of contents

+ + + +
+ +

1. Introduction

+ +

1.1. Dependencies

+ +

Some features of this specification are specific to CSS, or have + particular limitations or rules specific to CSS. In this + specification, these have been described in terms of CSS2.1. [CSS21]

+ +

1.2. Terminology

+ +

All of the text of this specification is normative except + examples, notes, and sections explicitly marked as + non-normative.

+ +

1.3. Changes from CSS2

+ +

This section is non-normative.

+ +

The main differences between the selectors in CSS2 and those in + Selectors are: + +

+ +

2. Selectors

+ +

This section is non-normative, as it merely summarizes the +following sections.

+ +

A Selector represents a structure. This structure can be used as a +condition (e.g. in a CSS rule) that determines which elements a +selector matches in the document tree, or as a flat description of the +HTML or XML fragment corresponding to that structure.

+ +

Selectors may range from simple element names to rich contextual +representations.

+ +

The following table summarizes the Selector syntax:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PatternMeaningDescribed in sectionFirst defined in CSS level
*any elementUniversal + selector2
Ean element of type EType selector1
E[foo]an E element with a "foo" attributeAttribute + selectors2
E[foo="bar"]an E element whose "foo" attribute value is exactly + equal to "bar"Attribute + selectors2
E[foo~="bar"]an E element whose "foo" attribute value is a list of + space-separated values, one of which is exactly equal to "bar"Attribute + selectors2
E[foo^="bar"]an E element whose "foo" attribute value begins exactly + with the string "bar"Attribute + selectors3
E[foo$="bar"]an E element whose "foo" attribute value ends exactly + with the string "bar"Attribute + selectors3
E[foo*="bar"]an E element whose "foo" attribute value contains the + substring "bar"Attribute + selectors3
E[hreflang|="en"]an E element whose "hreflang" attribute has a hyphen-separated + list of values beginning (from the left) with "en"Attribute + selectors2
E:rootan E element, root of the documentStructural + pseudo-classes3
E:nth-child(n)an E element, the n-th child of its parentStructural + pseudo-classes3
E:nth-last-child(n)an E element, the n-th child of its parent, counting + from the last oneStructural + pseudo-classes3
E:nth-of-type(n)an E element, the n-th sibling of its typeStructural + pseudo-classes3
E:nth-last-of-type(n)an E element, the n-th sibling of its type, counting + from the last oneStructural + pseudo-classes3
E:first-childan E element, first child of its parentStructural + pseudo-classes2
E:last-childan E element, last child of its parentStructural + pseudo-classes3
E:first-of-typean E element, first sibling of its typeStructural + pseudo-classes3
E:last-of-typean E element, last sibling of its typeStructural + pseudo-classes3
E:only-childan E element, only child of its parentStructural + pseudo-classes3
E:only-of-typean E element, only sibling of its typeStructural + pseudo-classes3
E:emptyan E element that has no children (including text + nodes)Structural + pseudo-classes3
E:link
E:visited
an E element being the source anchor of a hyperlink of + which the target is not yet visited (:link) or already visited + (:visited)The link + pseudo-classes1
E:active
E:hover
E:focus
an E element during certain user actionsThe user + action pseudo-classes1 and 2
E:targetan E element being the target of the referring URIThe target + pseudo-class3
E:lang(fr)an element of type E in language "fr" (the document + language specifies how language is determined)The :lang() + pseudo-class2
E:enabled
E:disabled
a user interface element E which is enabled or + disabledThe UI element states + pseudo-classes3
E:checkeda user interface element E which is checked (for instance a radio-button or checkbox)The UI element states + pseudo-classes3
E::first-linethe first formatted line of an E elementThe ::first-line + pseudo-element1
E::first-letterthe first formatted letter of an E elementThe ::first-letter + pseudo-element1
E::selectionthe portion of an E element that is currently + selected/highlighted by the userThe UI element + fragments pseudo-elements3
E::beforegenerated content before an E elementThe ::before + pseudo-element2
E::aftergenerated content after an E elementThe ::after + pseudo-element2
E.warningan E element whose class is +"warning" (the document language specifies how class is determined).Class + selectors1
E#myidan E element with ID equal to "myid".ID + selectors1
E:not(s)an E element that does not match simple selector sNegation + pseudo-class3
E Fan F element descendant of an E elementDescendant + combinator1
E > Fan F element child of an E elementChild + combinator2
E + Fan F element immediately preceded by an E elementAdjacent sibling combinator2
E ~ Fan F element preceded by an E elementGeneral sibling combinator3
+ +

The meaning of each selector is derived from the table above by +prepending "matches" to the contents of each cell in the "Meaning" +column.

+ +

3. Case sensitivity

+ +

The case sensitivity of document language element names, attribute +names, and attribute values in selectors depends on the document +language. For example, in HTML, element names are case-insensitive, +but in XML, they are case-sensitive.

+ +

4. Selector syntax

+ +

A selector is a chain of one +or more sequences of simple selectors +separated by combinators.

+ +

A sequence of simple selectors +is a chain of simple selectors +that are not separated by a combinator. It +always begins with a type selector or a +universal selector. No other type +selector or universal selector is allowed in the sequence.

+ +

A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, content selector, or pseudo-class. One pseudo-element may be appended to the last +sequence of simple selectors.

+ +

Combinators are: white space, "greater-than +sign" (U+003E, >), "plus sign" (U+002B, ++) and "tilde" (U+007E, ~). White +space may appear between a combinator and the simple selectors around +it. Only the characters "space" (U+0020), "tab" +(U+0009), "line feed" (U+000A), "carriage return" (U+000D), and "form +feed" (U+000C) can occur in white space. Other space-like characters, +such as "em-space" (U+2003) and "ideographic space" (U+3000), are +never part of white space.

+ +

The elements of a document tree that are represented by a selector +are the subjects of the selector. A +selector consisting of a single sequence of simple selectors +represents any element satisfying its requirements. Prepending another +sequence of simple selectors and a combinator to a sequence imposes +additional matching constraints, so the subjects of a selector are +always a subset of the elements represented by the last sequence of +simple selectors.

+ +

An empty selector, containing no sequence of simple selectors and +no pseudo-element, is an invalid +selector.

+ +

5. Groups of selectors

+ +

When several selectors share the same declarations, they may be +grouped into a comma-separated list. (A comma is U+002C.)

+ +
+

CSS examples:

+

In this example, we condense three rules with identical +declarations into one. Thus,

+
h1 { font-family: sans-serif }
+h2 { font-family: sans-serif }
+h3 { font-family: sans-serif }
+

is equivalent to:

+
h1, h2, h3 { font-family: sans-serif }
+
+ +

Warning: the equivalence is true in this example +because all the selectors are valid selectors. If just one of these +selectors were invalid, the entire group of selectors would be +invalid. This would invalidate the rule for all three heading +elements, whereas in the former case only one of the three individual +heading rules would be invalidated.

+ + +

6. Simple selectors

+ +

6.1. Type selector

+ +

A type selector is the name of a document language +element type. A type selector represents an instance of the element +type in the document tree.

+ +
+

Example:

+

The following selector represents an h1 element in the document tree:

+
h1
+
+ + +

6.1.1. Type selectors and namespaces

+ +

Type selectors allow an optional namespace ([XMLNAMES]) component. A namespace prefix +that has been previously declared may be prepended to the element name +separated by the namespace separator "vertical bar" +(U+007C, |).

+ +

The namespace component may be left empty to indicate that the +selector is only to represent elements with no declared namespace.

+ +

An asterisk may be used for the namespace prefix, indicating that +the selector represents elements in any namespace (including elements +with no namespace).

+ +

Element type selectors that have no namespace component (no +namespace separator), represent elements without regard to the +element's namespace (equivalent to "*|") unless a default +namespace has been declared. If a default namespace has been declared, +the selector will represent only elements in the default +namespace.

+ +

A type selector containing a namespace prefix that has not been +previously declared is an invalid selector. +The mechanism for declaring a namespace prefix is left up to the +language implementing Selectors. In CSS, such a mechanism is defined +in the General Syntax module.

+ +

In a namespace-aware client, element type selectors will only match +against the local part +of the element's qualified +name. See below for notes about matching +behaviors in down-level clients.

+ +

In summary:

+ +
+
ns|E
+
elements with name E in namespace ns
+
*|E
+
elements with name E in any namespace, including those without any + declared namespace
+
|E
+
elements with name E without any declared namespace
+
E
+
if no default namespace has been specified, this is equivalent to *|E. + Otherwise it is equivalent to ns|E where ns is the default namespace.
+
+ +
+

CSS examples:

+ +
@namespace foo url(http://www.example.com);
+ foo|h1 { color: blue }
+ foo|* { color: yellow }
+ |h1 { color: red }
+ *|h1 { color: green }
+ h1 { color: green }
+ +

The first rule will match only h1 elements in the + "http://www.example.com" namespace.

+ +

The second rule will match all elements in the + "http://www.example.com" namespace.

+ +

The third rule will match only h1 elements without + any declared namespace.

+ +

The fourth rule will match h1 elements in any + namespace (including those without any declared namespace).

+ +

The last rule is equivalent to the fourth rule because no default + namespace has been defined.

+ +
+ +

6.2. Universal selector

+ +

The universal selector, written "asterisk" +(*), represents the qualified name of any element +type. It represents any single element in the document tree in any +namespace (including those without any declared namespace) if no +default namespace has been specified. If a default namespace has been +specified, see Universal selector and +Namespaces below.

+ +

If the universal selector is not the only component of a sequence +of simple selectors, the * may be omitted.

+ +
+

Examples:

+
    +
  • *[hreflang|=en] and [hreflang|=en] are equivalent,
  • +
  • *.warning and .warning are equivalent,
  • +
  • *#myid and #myid are equivalent.
  • +
+
+ +

Note: it is recommended that the +*, representing the universal selector, not be +omitted.

+ +

6.2.1. Universal selector and namespaces

+ +

The universal selector allows an optional namespace component. It +is used as follows:

+ +
+
ns|*
+
all elements in namespace ns
+
*|*
+
all elements
+
|*
+
all elements without any declared namespace
+
*
+
if no default namespace has been specified, this is equivalent to *|*. + Otherwise it is equivalent to ns|* where ns is the default namespace.
+
+ +

A universal selector containing a namespace prefix that has not +been previously declared is an invalid +selector. The mechanism for declaring a namespace prefix is left up +to the language implementing Selectors. In CSS, such a mechanism is +defined in the General Syntax module.

+ + +

6.3. Attribute selectors

+ +

Selectors allow the representation of an element's attributes. When +a selector is used as an expression to match against an element, +attribute selectors must be considered to match an element if that +element has an attribute that matches the attribute represented by the +attribute selector.

+ +

6.3.1. Attribute presence and values +selectors

+ +

CSS2 introduced four attribute selectors:

+ +
+
[att] +
Represents an element with the att attribute, whatever the value of + the attribute.
+
[att=val]
+
Represents an element with the att attribute whose value is exactly + "val".
+
[att~=val]
+
Represents an element with the att attribute whose value is a whitespace-separated list of words, one of + which is exactly "val". If "val" contains whitespace, it will never + represent anything (since the words are separated by + spaces).
+
[att|=val] +
Represents an element with the att attribute, its value either + being exactly "val" or beginning with "val" immediately followed by + "-" (U+002D). This is primarily intended to allow language subcode + matches (e.g., the hreflang attribute on the + link element in HTML) as described in RFC 3066 ([RFC3066]). For lang (or + xml:lang) language subcode matching, please see the :lang pseudo-class.
+
+ +

Attribute values must be identifiers or strings. The +case-sensitivity of attribute names and values in selectors depends on +the document language.

+ +
+ +

Examples:

+ +

The following attribute selector represents an h1 + element that carries the title attribute, whatever its + value:

+ +
h1[title]
+ +

In the following example, the selector represents a + span element whose class attribute has + exactly the value "example":

+ +
span[class="example"]
+ +

Multiple attribute selectors can be used to represent several + attributes of an element, or several conditions on the same + attribute. Here, the selector represents a span element + whose hello attribute has exactly the value "Cleveland" + and whose goodbye attribute has exactly the value + "Columbus":

+ +
span[hello="Cleveland"][goodbye="Columbus"]
+ +

The following selectors illustrate the differences between "=" + and "~=". The first selector will represent, for example, the value + "copyright copyleft copyeditor" on a rel attribute. The + second selector will only represent an a element with + an href attribute having the exact value + "http://www.w3.org/".

+ +
a[rel~="copyright"]
+a[href="http://www.w3.org/"]
+ +

The following selector represents a link element + whose hreflang attribute is exactly "fr".

+ +
link[hreflang=fr]
+ +

The following selector represents a link element for + which the values of the hreflang attribute begins with + "en", including "en", "en-US", and "en-cockney":

+ +
link[hreflang|="en"]
+ +

Similarly, the following selectors represents a + DIALOGUE element whenever it has one of two different + values for an attribute character:

+ +
DIALOGUE[character=romeo]
+DIALOGUE[character=juliet]
+ +
+ +

6.3.2. Substring matching attribute +selectors

+ +

Three additional attribute selectors are provided for matching +substrings in the value of an attribute:

+ +
+
[att^=val]
+
Represents an element with the att attribute whose value begins + with the prefix "val".
+
[att$=val] +
Represents an element with the att attribute whose value ends with + the suffix "val".
+
[att*=val] +
Represents an element with the att attribute whose value contains + at least one instance of the substring "val".
+
+ +

Attribute values must be identifiers or strings. The +case-sensitivity of attribute names in selectors depends on the +document language.

+ +
+

Examples:

+

The following selector represents an HTML object, referencing an + image:

+
object[type^="image/"]
+

The following selector represents an HTML anchor a with an + href attribute whose value ends with ".html".

+
a[href$=".html"]
+

The following selector represents an HTML paragraph with a title + attribute whose value contains the substring "hello"

+
p[title*="hello"]
+
+ +

6.3.3. Attribute selectors and namespaces

+ +

Attribute selectors allow an optional namespace component to the +attribute name. A namespace prefix that has been previously declared +may be prepended to the attribute name separated by the namespace +separator "vertical bar" (|). In keeping with +the Namespaces in the XML recommendation, default namespaces do not +apply to attributes, therefore attribute selectors without a namespace +component apply only to attributes that have no declared namespace +(equivalent to "|attr"). An asterisk may be used for the +namespace prefix indicating that the selector is to match all +attribute names without regard to the attribute's namespace. + +

An attribute selector with an attribute name containing a namespace +prefix that has not been previously declared is an invalid selector. The mechanism for declaring +a namespace prefix is left up to the language implementing Selectors. +In CSS, such a mechanism is defined in the General Syntax module. + +

+

CSS examples:

+
@namespace foo "http://www.example.com";
+[foo|att=val] { color: blue }
+[*|att] { color: yellow }
+[|att] { color: green }
+[att] { color: green }
+ +

The first rule will match only elements with the attribute + att in the "http://www.example.com" namespace with the + value "val".

+ +

The second rule will match only elements with the attribute + att regardless of the namespace of the attribute + (including no declared namespace).

+ +

The last two rules are equivalent and will match only elements + with the attribute att where the attribute is not + declared to be in a namespace.

+ +
+ +

6.3.4. Default attribute values in DTDs

+ +

Attribute selectors represent explicitly set attribute values in +the document tree. Default attribute values may be defined in a DTD or +elsewhere, but cannot always be selected by attribute +selectors. Selectors should be designed so that they work even if the +default values are not included in the document tree.

+ +

More precisely, a UA is not required to read an "external +subset" of the DTD but is required to look for default +attribute values in the document's "internal subset." (See [XML10] for definitions of these subsets.)

+ +

A UA that recognizes an XML namespace [XMLNAMES] is not required to use its +knowledge of that namespace to treat default attribute values as if +they were present in the document. (For example, an XHTML UA is not +required to use its built-in knowledge of the XHTML DTD.)

+ +

Note: Typically, implementations +choose to ignore external subsets.

+ +
+

Example:

+ +

Consider an element EXAMPLE with an attribute "notation" that has a +default value of "decimal". The DTD fragment might be

+ +
<!ATTLIST EXAMPLE notation (decimal,octal) "decimal">
+ +

If the style sheet contains the rules

+ +
EXAMPLE[notation=decimal] { /*... default property settings ...*/ }
+EXAMPLE[notation=octal]   { /*... other settings...*/ }
+ +

the first rule will not match elements whose "notation" attribute +is set by default, i.e. not set explicitly. To catch all cases, the +attribute selector for the default value must be dropped:

+ +
EXAMPLE                   { /*... default property settings ...*/ }
+EXAMPLE[notation=octal]   { /*... other settings...*/ }
+ +

Here, because the selector EXAMPLE[notation=octal] is +more specific than the tag +selector alone, the style declarations in the second rule will override +those in the first for elements that have a "notation" attribute value +of "octal". Care has to be taken that all property declarations that +are to apply only to the default case are overridden in the non-default +cases' style rules.

+ +
+ +

6.4. Class selectors

+ +

Working with HTML, authors may use the period (U+002E, +.) notation as an alternative to the ~= +notation when representing the class attribute. Thus, for +HTML, div.value and div[class~=value] have +the same meaning. The attribute value must immediately follow the +"period" (.).

+ +

UAs may apply selectors using the period (.) notation in XML +documents if the UA has namespace-specific knowledge that allows it to +determine which attribute is the "class" attribute for the +respective namespace. One such example of namespace-specific knowledge +is the prose in the specification for a particular namespace (e.g. SVG +1.0 [SVG] describes the SVG +"class" attribute and how a UA should interpret it, and +similarly MathML 1.01 [MATH] describes the MathML +"class" attribute.)

+ +
+

CSS examples:

+ +

We can assign style information to all elements with + class~="pastoral" as follows:

+ +
*.pastoral { color: green }  /* all elements with class~=pastoral */
+ +

or just

+ +
.pastoral { color: green }  /* all elements with class~=pastoral */
+ +

The following assigns style only to H1 elements with + class~="pastoral":

+ +
H1.pastoral { color: green }  /* H1 elements with class~=pastoral */
+ +

Given these rules, the first H1 instance below would not have + green text, while the second would:

+ +
<H1>Not green</H1>
+<H1 class="pastoral">Very green</H1>
+ +
+ +

To represent a subset of "class" values, each value must be preceded +by a ".", in any order.

+ +
+ +

CSS example:

+ +

The following rule matches any P element whose "class" attribute + has been assigned a list of whitespace-separated values that includes + "pastoral" and "marine":

+ +
p.pastoral.marine { color: green }
+ +

This rule matches when class="pastoral blue aqua + marine" but does not match for class="pastoral + blue".

+ +
+ +

Note: Because CSS gives considerable +power to the "class" attribute, authors could conceivably design their +own "document language" based on elements with almost no associated +presentation (such as DIV and SPAN in HTML) and assigning style +information through the "class" attribute. Authors should avoid this +practice since the structural elements of a document language often +have recognized and accepted meanings and author-defined classes may +not.

+ +

Note: If an element has multiple +class attributes, their values must be concatenated with spaces +between the values before searching for the class. As of this time the +working group is not aware of any manner in which this situation can +be reached, however, so this behavior is explicitly non-normative in +this specification.

+ +

6.5. ID selectors

+ +

Document languages may contain attributes that are declared to be +of type ID. What makes attributes of type ID special is that no two +such attributes can have the same value in a document, regardless of +the type of the elements that carry them; whatever the document +language, an ID typed attribute can be used to uniquely identify its +element. In HTML all ID attributes are named "id"; XML applications +may name ID attributes differently, but the same restriction +applies.

+ +

An ID-typed attribute of a document language allows authors to +assign an identifier to one element instance in the document tree. W3C +ID selectors represent an element instance based on its identifier. An +ID selector contains a "number sign" (U+0023, +#) immediately followed by the ID value, which must be an +identifier.

+ +

Selectors does not specify how a UA knows the ID-typed attribute of +an element. The UA may, e.g., read a document's DTD, have the +information hard-coded or ask the user. + +

+

Examples:

+

The following ID selector represents an h1 element + whose ID-typed attribute has the value "chapter1":

+
h1#chapter1
+

The following ID selector represents any element whose ID-typed + attribute has the value "chapter1":

+
#chapter1
+

The following selector represents any element whose ID-typed + attribute has the value "z98y".

+
*#z98y
+
+ +

Note. In XML 1.0 [XML10], the information about which attribute +contains an element's IDs is contained in a DTD or a schema. When +parsing XML, UAs do not always read the DTD, and thus may not know +what the ID of an element is (though a UA may have namespace-specific +knowledge that allows it to determine which attribute is the ID +attribute for that namespace). If a style sheet designer knows or +suspects that a UA may not know what the ID of an element is, he +should use normal attribute selectors instead: +[name=p371] instead of #p371. Elements in +XML 1.0 documents without a DTD do not have IDs at all.

+ +

If an element has multiple ID attributes, all of them must be +treated as IDs for that element for the purposes of the ID +selector. Such a situation could be reached using mixtures of xml:id, +DOM3 Core, XML DTDs, and namespace-specific knowledge.

+ +

6.6. Pseudo-classes

+ +

The pseudo-class concept is introduced to permit selection based on +information that lies outside of the document tree or that cannot be +expressed using the other simple selectors.

+ +

A pseudo-class always consists of a "colon" +(:) followed by the name of the pseudo-class and +optionally by a value between parentheses.

+ +

Pseudo-classes are allowed in all sequences of simple selectors +contained in a selector. Pseudo-classes are allowed anywhere in +sequences of simple selectors, after the leading type selector or +universal selector (possibly omitted). Pseudo-class names are +case-insensitive. Some pseudo-classes are mutually exclusive, while +others can be applied simultaneously to the same +element. Pseudo-classes may be dynamic, in the sense that an element +may acquire or lose a pseudo-class while a user interacts with the +document.

+ + +

6.6.1. Dynamic pseudo-classes

+ +

Dynamic pseudo-classes classify elements on characteristics other +than their name, attributes, or content, in principle characteristics +that cannot be deduced from the document tree.

+ +

Dynamic pseudo-classes do not appear in the document source or +document tree.

+ + +
The link pseudo-classes: :link and :visited
+ +

User agents commonly display unvisited links differently from +previously visited ones. Selectors +provides the pseudo-classes :link and +:visited to distinguish them:

+ + + +

After some amount of time, user agents may choose to return a +visited link to the (unvisited) ':link' state.

+ +

The two states are mutually exclusive.

+ +
+ +

Example:

+ +

The following selector represents links carrying class + external and already visited:

+ +
a.external:visited
+ +
+ +

Note: It is possible for style sheet +authors to abuse the :link and :visited pseudo-classes to determine +which sites a user has visited without the user's consent. + +

UAs may therefore treat all links as unvisited links, or implement +other measures to preserve the user's privacy while rendering visited +and unvisited links differently.

+ +
The user action pseudo-classes +:hover, :active, and :focus
+ +

Interactive user agents sometimes change the rendering in response +to user actions. Selectors provides +three pseudo-classes for the selection of an element the user is +acting on.

+ + + +

There may be document language or implementation specific limits on +which elements can become :active or acquire +:focus.

+ +

These pseudo-classes are not mutually exclusive. An element may +match several pseudo-classes at the same time.

+ +

Selectors doesn't define if the parent of an element that is +':active' or ':hover' is also in that state.

+ +
+

Examples:

+
a:link    /* unvisited links */
+a:visited /* visited links */
+a:hover   /* user hovers */
+a:active  /* active links */
+

An example of combining dynamic pseudo-classes:

+
a:focus
+a:focus:hover
+

The last selector matches a elements that are in + the pseudo-class :focus and in the pseudo-class :hover.

+
+ +

Note: An element can be both ':visited' +and ':active' (or ':link' and ':active').

+ +

6.6.2. The target pseudo-class :target

+ +

Some URIs refer to a location within a resource. This kind of URI +ends with a "number sign" (#) followed by an anchor +identifier (called the fragment identifier).

+ +

URIs with fragment identifiers link to a certain element within the +document, known as the target element. For instance, here is a URI +pointing to an anchor named section_2 in an HTML +document:

+ +
http://example.com/html/top.html#section_2
+ +

A target element can be represented by the :target +pseudo-class. If the document's URI has no fragment identifier, then +the document has no target element.

+ +
+

Example:

+
p.note:target
+

This selector represents a p element of class + note that is the target element of the referring + URI.

+
+ +
+

CSS example:

+

Here, the :target pseudo-class is used to make the + target element red and place an image before it, if there is one:

+
*:target { color : red }
+*:target::before { content : url(target.png) }
+
+ +

6.6.3. The language pseudo-class :lang

+ +

If the document language specifies how the human language of an +element is determined, it is possible to write selectors that +represent an element based on its language. For example, in HTML [HTML4], the language is determined by a +combination of the lang attribute, the meta +element, and possibly by information from the protocol (such as HTTP +headers). XML uses an attribute called xml:lang, and +there may be other document language-specific methods for determining +the language.

+ +

The pseudo-class :lang(C) represents an element that +is in language C. Whether an element is represented by a +:lang() selector is based solely on the identifier C +being either equal to, or a hyphen-separated substring of, the +element's language value, in the same way as if performed by the '|=' operator in attribute +selectors. The identifier C does not have to be a valid language +name.

+ +

C must not be empty. (If it is, the selector is invalid.)

+ +

Note: It is recommended that +documents and protocols indicate language using codes from RFC 3066 [RFC3066] or its successor, and by means of +"xml:lang" attributes in the case of XML-based documents [XML10]. See +"FAQ: Two-letter or three-letter language codes."

+ +
+

Examples:

+

The two following selectors represent an HTML document that is in + Belgian, French, or German. The two next selectors represent + q quotations in an arbitrary element in Belgian, French, + or German.

+
html:lang(fr-be)
+html:lang(de)
+:lang(fr-be) > q
+:lang(de) > q
+
+ +

6.6.4. The UI element states pseudo-classes

+ +
The :enabled and :disabled pseudo-classes
+ +

The :enabled pseudo-class allows authors to customize +the look of user interface elements that are enabled — which the +user can select or activate in some fashion (e.g. clicking on a button +with a mouse). There is a need for such a pseudo-class because there +is no way to programmatically specify the default appearance of say, +an enabled input element without also specifying what it +would look like when it was disabled.

+ +

Similar to :enabled, :disabled allows the +author to specify precisely how a disabled or inactive user interface +element should look.

+ +

Most elements will be neither enabled nor disabled. An element is +enabled if the user can either activate it or transfer the focus to +it. An element is disabled if it could be enabled, but the user cannot +presently activate it or transfer focus to it.

+ + +
The :checked pseudo-class
+ +

Radio and checkbox elements can be toggled by the user. Some menu +items are "checked" when the user selects them. When such elements are +toggled "on" the :checked pseudo-class applies. The +:checked pseudo-class initially applies to such elements +that have the HTML4 selected and checked +attributes as described in Section +17.2.1 of HTML4, but of course the user can toggle "off" such +elements in which case the :checked pseudo-class would no +longer apply. While the :checked pseudo-class is dynamic +in nature, and is altered by user action, since it can also be based +on the presence of the semantic HTML4 selected and +checked attributes, it applies to all media. + + +

The :indeterminate pseudo-class
+ +
+ +

Radio and checkbox elements can be toggled by the user, but are +sometimes in an indeterminate state, neither checked nor unchecked. +This can be due to an element attribute, or DOM manipulation.

+ +

A future version of this specification may introduce an +:indeterminate pseudo-class that applies to such elements. +

+ +
+ + +

6.6.5. Structural pseudo-classes

+ +

Selectors introduces the concept of structural +pseudo-classes to permit selection based on extra information that lies in +the document tree but cannot be represented by other simple selectors or +combinators. + +

Note that standalone pieces of PCDATA (text nodes in the DOM) are +not counted when calculating the position of an element in the list of +children of its parent. When calculating the position of an element in +the list of children of its parent, the index numbering starts at 1. + + +

:root pseudo-class
+ +

The :root pseudo-class represents an element that is +the root of the document. In HTML 4, this is always the +HTML element. + + +

:nth-child() pseudo-class
+ +

The +:nth-child(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings +before it in the document tree, for a given positive +integer or zero value of n, and has a parent element. In +other words, this matches the bth child of an element after +all the children have been split into groups of a elements +each. For example, this allows the selectors to address every other +row in a table, and could be used to alternate the color +of paragraph text in a cycle of four. The a and +b values must be zero, negative integers or positive +integers. The index of the first child of an element is 1. + +

In addition to this, :nth-child() can take +'odd' and 'even' as arguments instead. +'odd' has the same signification as 2n+1, +and 'even' has the same signification as 2n. + + +

+

Examples:

+
tr:nth-child(2n+1) /* represents every odd row of an HTML table */
+tr:nth-child(odd)  /* same */
+tr:nth-child(2n)   /* represents every even row of an HTML table */
+tr:nth-child(even) /* same */
+
+/* Alternate paragraph colours in CSS */
+p:nth-child(4n+1) { color: navy; }
+p:nth-child(4n+2) { color: green; }
+p:nth-child(4n+3) { color: maroon; }
+p:nth-child(4n+4) { color: purple; }
+
+ +

When a=0, no repeating is used, so for example +:nth-child(0n+5) matches only the fifth child. When +a=0, the an part need not be +included, so the syntax simplifies to +:nth-child(b) and the last example simplifies +to :nth-child(5). + +

+

Examples:

+
foo:nth-child(0n+1)   /* represents an element foo, first child of its parent element */
+foo:nth-child(1)      /* same */
+
+ +

When a=1, the number may be omitted from the rule. + +

+

Examples:

+

The following selectors are therefore equivalent:

+
bar:nth-child(1n+0)   /* represents all bar elements, specificity (0,1,1) */
+bar:nth-child(n+0)    /* same */
+bar:nth-child(n)      /* same */
+bar                   /* same but lower specificity (0,0,1) */
+
+ +

If b=0, then every ath element is picked. In +such a case, the b part may be omitted. + +

+

Examples:

+
tr:nth-child(2n+0) /* represents every even row of an HTML table */
+tr:nth-child(2n) /* same */
+
+ +

If both a and b are equal to zero, the +pseudo-class represents no element in the document tree.

+ +

The value a can be negative, but only the positive +values of an+b, for +n≥0, may represent an element in the document +tree.

+ +
+

Example:

+
html|tr:nth-child(-n+6)  /* represents the 6 first rows of XHTML tables */
+
+ +

When the value b is negative, the "+" character in the +expression must be removed (it is effectively replaced by the "-" +character indicating the negative value of b).

+ +
+

Examples:

+
:nth-child(10n-1)  /* represents the 9th, 19th, 29th, etc, element */
+:nth-child(10n+9)  /* Same */
+:nth-child(10n+-1) /* Syntactically invalid, and would be ignored */
+
+ + +
:nth-last-child() pseudo-class
+ +

The :nth-last-child(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings +after it in the document tree, for a given positive +integer or zero value of n, and has a parent element. See +:nth-child() pseudo-class for the syntax of its argument. +It also accepts the 'even' and 'odd' values +as arguments. + + +

+

Examples:

+
tr:nth-last-child(-n+2)    /* represents the two last rows of an HTML table */
+
+foo:nth-last-child(odd)    /* represents all odd foo elements in their parent element,
+                              counting from the last one */
+
+ + +
:nth-of-type() pseudo-class
+ +

The :nth-of-type(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings with the same +element name before it in the document tree, for a +given zero or positive integer value of n, and has a +parent element. In other words, this matches the bth child +of that type after all the children of that type have been split into +groups of a elements each. See :nth-child() pseudo-class +for the syntax of its argument. It also accepts the +'even' and 'odd' values. + + +

+

CSS example:

+

This allows an author to alternate the position of floated images:

+
img:nth-of-type(2n+1) { float: right; }
+img:nth-of-type(2n) { float: left; }
+
+ + +
:nth-last-of-type() pseudo-class
+ +

The :nth-last-of-type(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings with the same +element name after it in the document tree, for a +given zero or positive integer value of n, and has a +parent element. See :nth-child() pseudo-class for the +syntax of its argument. It also accepts the 'even' and 'odd' values. + + +

+

Example:

+

To represent all h2 children of an XHTML + body except the first and last, one could use the + following selector:

+
body > h2:nth-of-type(n+2):nth-last-of-type(n+2)
+

In this case, one could also use :not(), although the + selector ends up being just as long:

+
body > h2:not(:first-of-type):not(:last-of-type)
+
+ + +
:first-child pseudo-class
+ +

Same as :nth-child(1). The :first-child pseudo-class +represents an element that is the first child of some other element. + + +

+

Examples:

+

The following selector represents a p element that is + the first child of a div element:

+
div > p:first-child
+

This selector can represent the p inside the + div of the following fragment:

+
<p> The last P before the note.</p>
+<div class="note">
+   <p> The first P inside the note.</p>
+</div>
but cannot represent the second p in the following +fragment: +
<p> The last P before the note.</p>
+<div class="note">
+   <h2> Note </h2>
+   <p> The first P inside the note.</p>
+</div>
+

The following two selectors are usually equivalent:

+
* > a:first-child /* a is first child of any element */
+a:first-child /* Same (assuming a is not the root element) */
+
+ +
:last-child pseudo-class
+ +

Same as :nth-last-child(1). The :last-child pseudo-class +represents an element that is the last child of some other element. + +

+

Example:

+

The following selector represents a list item li that + is the last child of an ordered list ol. +

ol > li:last-child
+
+ +
:first-of-type pseudo-class
+ +

Same as :nth-of-type(1). The :first-of-type pseudo-class +represents an element that is the first sibling of its type in the list of +children of its parent element. + +

+

Example:

+

The following selector represents a definition title +dt inside a definition list dl, this +dt being the first of its type in the list of children of +its parent element.

+
dl dt:first-of-type
+

It is a valid description for the first two dt +elements in the following example but not for the third one:

+
<dl>
+ <dt>gigogne</dt>
+ <dd>
+  <dl>
+   <dt>fusée</dt>
+   <dd>multistage rocket</dd>
+   <dt>table</dt>
+   <dd>nest of tables</dd>
+  </dl>
+ </dd>
+</dl>
+
+ +
:last-of-type pseudo-class
+ +

Same as :nth-last-of-type(1). The +:last-of-type pseudo-class represents an element that is +the last sibling of its type in the list of children of its parent +element.

+ +
+

Example:

+

The following selector represents the last data cell + td of a table row.

+
tr > td:last-of-type
+
+ +
:only-child pseudo-class
+ +

Represents an element that has a parent element and whose parent +element has no other element children. Same as +:first-child:last-child or +:nth-child(1):nth-last-child(1), but with a lower +specificity.

+ +
:only-of-type pseudo-class
+ +

Represents an element that has a parent element and whose parent +element has no other element children with the same element name. Same +as :first-of-type:last-of-type or +:nth-of-type(1):nth-last-of-type(1), but with a lower +specificity.

+ + +
:empty pseudo-class
+ +

The :empty pseudo-class represents an element that has +no children at all. In terms of the DOM, only element nodes and text +nodes (including CDATA nodes and entity references) whose data has a +non-zero length must be considered as affecting emptiness; comments, +PIs, and other nodes must not affect whether an element is considered +empty or not.

+ +
+

Examples:

+

p:empty is a valid representation of the following fragment:

+
<p></p>
+

foo:empty is not a valid representation for the + following fragments:

+
<foo>bar</foo>
+
<foo><bar>bla</bar></foo>
+
<foo>this is not <bar>:empty</bar></foo>
+
+ +

6.6.6. Blank

+ +

This section intentionally left blank.

+ + +

6.6.7. The negation pseudo-class

+ +

The negation pseudo-class, :not(X), is a +functional notation taking a simple +selector (excluding the negation pseudo-class itself and +pseudo-elements) as an argument. It represents an element that is not +represented by the argument. + + + +

+

Examples:

+

The following CSS selector matches all button + elements in an HTML document that are not disabled.

+
button:not([DISABLED])
+

The following selector represents all but FOO + elements.

+
*:not(FOO)
+

The following group of selectors represents all HTML elements + except links.

+
html|*:not(:link):not(:visited)
+
+ +

Default namespace declarations do not affect the argument of the +negation pseudo-class unless the argument is a universal selector or a +type selector.

+ +
+

Examples:

+

Assuming that the default namespace is bound to + "http://example.com/", the following selector represents all + elements that are not in that namespace:

+
*|*:not(*)
+

The following CSS selector matches any element being hovered, + regardless of its namespace. In particular, it is not limited to + only matching elements in the default namespace that are not being + hovered, and elements not in the default namespace don't match the + rule when they are being hovered.

+
*|*:not(:hover)
+
+ +

Note: the :not() pseudo allows +useless selectors to be written. For instance :not(*|*), +which represents no element at all, or foo:not(bar), +which is equivalent to foo but with a higher +specificity.

+ +

7. Pseudo-elements

+ +

Pseudo-elements create abstractions about the document tree beyond +those specified by the document language. For instance, document +languages do not offer mechanisms to access the first letter or first +line of an element's content. Pseudo-elements allow designers to refer +to this otherwise inaccessible information. Pseudo-elements may also +provide designers a way to refer to content that does not exist in the +source document (e.g., the ::before and +::after pseudo-elements give access to generated +content).

+ +

A pseudo-element is made of two colons (::) followed +by the name of the pseudo-element.

+ +

This :: notation is introduced by the current document +in order to establish a discrimination between pseudo-classes and +pseudo-elements. For compatibility with existing style sheets, user +agents must also accept the previous one-colon notation for +pseudo-elements introduced in CSS levels 1 and 2 (namely, +:first-line, :first-letter, +:before and :after). This compatibility is +not allowed for the new pseudo-elements introduced in CSS level 3.

+ +

Only one pseudo-element may appear per selector, and if present it +must appear after the sequence of simple selectors that represents the +subjects of the selector. A +future version of this specification may allow multiple +pesudo-elements per selector.

+ +

7.1. The ::first-line pseudo-element

+ +

The ::first-line pseudo-element describes the contents +of the first formatted line of an element. + +

+

CSS example:

+
p::first-line { text-transform: uppercase }
+

The above rule means "change the letters of the first line of every +paragraph to uppercase".

+
+ +

The selector p::first-line does not match any real +HTML element. It does match a pseudo-element that conforming user +agents will insert at the beginning of every paragraph.

+ +

Note that the length of the first line depends on a number of +factors, including the width of the page, the font size, etc. Thus, +an ordinary HTML paragraph such as:

+ +
+<P>This is a somewhat long HTML 
+paragraph that will be broken into several 
+lines. The first line will be identified
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

the lines of which happen to be broken as follows: + +

+THIS IS A SOMEWHAT LONG HTML PARAGRAPH THAT
+will be broken into several lines. The first
+line will be identified by a fictional tag 
+sequence. The other lines will be treated as 
+ordinary lines in the paragraph.
+
+ +

This paragraph might be "rewritten" by user agents to include the +fictional tag sequence for ::first-line. This +fictional tag sequence helps to show how properties are inherited.

+ +
+<P><P::first-line> This is a somewhat long HTML 
+paragraph that </P::first-line> will be broken into several
+lines. The first line will be identified 
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

If a pseudo-element breaks up a real element, the desired effect +can often be described by a fictional tag sequence that closes and +then re-opens the element. Thus, if we mark up the previous paragraph +with a span element:

+ +
+<P><SPAN class="test"> This is a somewhat long HTML
+paragraph that will be broken into several
+lines.</SPAN> The first line will be identified
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

the user agent could simulate start and end tags for +span when inserting the fictional tag sequence for +::first-line. + +

+<P><P::first-line><SPAN class="test"> This is a
+somewhat long HTML
+paragraph that will </SPAN></P::first-line><SPAN class="test"> be
+broken into several
+lines.</SPAN> The first line will be identified
+by a fictional tag sequence. The other lines
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

In CSS, the ::first-line pseudo-element can only be +attached to a block-level element, an inline-block, a table-caption, +or a table-cell.

+ +

The "first formatted line" of an +element may occur inside a +block-level descendant in the same flow (i.e., a block-level +descendant that is not positioned and not a float). E.g., the first +line of the div in <DIV><P>This +line...</P></DIV> is the first line of the p (assuming +that both p and div are block-level). + +

The first line of a table-cell or inline-block cannot be the first +formatted line of an ancestor element. Thus, in <DIV><P +STYLE="display: inline-block">Hello<BR>Goodbye</P> +etcetera</DIV> the first formatted line of the +div is not the line "Hello". + +

Note that the first line of the p in this +fragment: <p><br>First... doesn't contain any +letters (assuming the default style for br in HTML +4). The word "First" is not on the first formatted line. + +

A UA should act as if the fictional start tags of the +::first-line pseudo-elements were nested just inside the +innermost enclosing block-level element. (Since CSS1 and CSS2 were +silent on this case, authors should not rely on this behavior.) Here +is an example. The fictional tag sequence for

+ +
+<DIV>
+  <P>First paragraph</P>
+  <P>Second paragraph</P>
+</DIV>
+
+ +

is

+ +
+<DIV>
+  <P><DIV::first-line><P::first-line>First paragraph</P::first-line></DIV::first-line></P>
+  <P><P::first-line>Second paragraph</P::first-line></P>
+</DIV>
+
+ +

The ::first-line pseudo-element is similar to an +inline-level element, but with certain restrictions. In CSS, the +following properties apply to a ::first-line +pseudo-element: font properties, color property, background +properties, 'word-spacing', 'letter-spacing', 'text-decoration', +'vertical-align', 'text-transform', 'line-height'. UAs may apply other +properties as well.

+ + +

7.2. The ::first-letter pseudo-element

+ +

The ::first-letter pseudo-element represents the first +letter of the first line of a block, if it is not preceded by any +other content (such as images or inline tables) on its line. The +::first-letter pseudo-element may be used for "initial caps" and "drop +caps", which are common typographical effects. This type of initial +letter is similar to an inline-level element if its 'float' property +is 'none'; otherwise, it is similar to a floated element.

+ +

In CSS, these are the properties that apply to ::first-letter +pseudo-elements: font properties, 'text-decoration', 'text-transform', +'letter-spacing', 'word-spacing' (when appropriate), 'line-height', +'float', 'vertical-align' (only if 'float' is 'none'), margin +properties, padding properties, border properties, color property, +background properties. UAs may apply other properties as well. To +allow UAs to render a typographically correct drop cap or initial cap, +the UA may choose a line-height, width and height based on the shape +of the letter, unlike for normal elements.

+ +
+

Example:

+

This example shows a possible rendering of an initial cap. Note +that the 'line-height' that is inherited by the ::first-letter +pseudo-element is 1.1, but the UA in this example has computed the +height of the first letter differently, so that it doesn't cause any +unnecessary space between the first two lines. Also note that the +fictional start tag of the first letter is inside the span, and thus +the font weight of the first letter is normal, not bold as the span: +

+p { line-height: 1.1 }
+p::first-letter { font-size: 3em; font-weight: normal }
+span { font-weight: bold }
+...
+<p><span>Het hemelsche</span> gerecht heeft zich ten lange lesten<br>
+Erbarremt over my en mijn benaeuwde vesten<br>
+En arme burgery, en op mijn volcx gebed<br>
+En dagelix geschrey de bange stad ontzet.
+
+
+

Image illustrating the ::first-letter pseudo-element +

+
+ +
+

The following CSS will make a drop cap initial letter span about two lines:

+ +
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<HTML>
+ <HEAD>
+  <TITLE>Drop cap initial letter</TITLE>
+  <STYLE type="text/css">
+   P               { font-size: 12pt; line-height: 1.2 }
+   P::first-letter { font-size: 200%; font-weight: bold; float: left }
+   SPAN            { text-transform: uppercase }
+  </STYLE>
+ </HEAD>
+ <BODY>
+  <P><SPAN>The first</SPAN> few words of an article
+    in The Economist.</P>
+ </BODY>
+</HTML>
+
+ +

This example might be formatted as follows:

+ +
+

Image illustrating the combined effect of the ::first-letter and ::first-line pseudo-elements

+
+ +

The fictional tag sequence is:

+ +
+<P>
+<SPAN>
+<P::first-letter>
+T
+</P::first-letter>he first
+</SPAN> 
+few words of an article in the Economist.
+</P>
+
+ +

Note that the ::first-letter pseudo-element tags abut +the content (i.e., the initial character), while the ::first-line +pseudo-element start tag is inserted right after the start tag of the +block element.

+ +

In order to achieve traditional drop caps formatting, user agents +may approximate font sizes, for example to align baselines. Also, the +glyph outline may be taken into account when formatting.

+ +

Punctuation (i.e, characters defined in Unicode in the "open" (Ps), +"close" (Pe), "initial" (Pi). "final" (Pf) and "other" (Po) +punctuation classes), that precedes or follows the first letter should +be included. [UNICODE]

+ +
+

Quotes that precede the
+first letter should be included.

+
+ +

The ::first-letter also applies if the first letter is +in fact a digit, e.g., the "6" in "67 million dollars is a lot of +money."

+ +

In CSS, the ::first-letter pseudo-element applies to +block, list-item, table-cell, table-caption, and inline-block +elements. A future version of this specification +may allow this pesudo-element to apply to more element +types.

+ +

The ::first-letter pseudo-element can be used with all +such elements that contain text, or that have a descendant in the same +flow that contains text. A UA should act as if the fictional start tag +of the ::first-letter pseudo-element is just before the first text of +the element, even if that first text is in a descendant.

+ +
+

Example:

+

The fictional tag sequence for this HTMLfragment: +

<div>
+<p>The first text.
+

is: +

<div>
+<p><div::first-letter><p::first-letter>T</...></...>he first text.
+
+ +

The first letter of a table-cell or inline-block cannot be the +first letter of an ancestor element. Thus, in <DIV><P +STYLE="display: inline-block">Hello<BR>Goodbye</P> +etcetera</DIV> the first letter of the div is not the +letter "H". In fact, the div doesn't have a first letter. + +

The first letter must occur on the first formatted line. For example, in +this fragment: <p><br>First... the first line +doesn't contain any letters and ::first-letter doesn't +match anything (assuming the default style for br in HTML +4). In particular, it does not match the "F" of "First." + +

In CSS, if an element is a list item ('display: list-item'), the +::first-letter applies to the first letter in the +principal box after the marker. UAs may ignore +::first-letter on list items with 'list-style-position: +inside'. If an element has ::before or +::after content, the ::first-letter applies +to the first letter of the element including that content. + +

+

Example:

+

After the rule 'p::before {content: "Note: "}', the selector +'p::first-letter' matches the "N" of "Note".

+
+ +

Some languages may have specific rules about how to treat certain +letter combinations. In Dutch, for example, if the letter combination +"ij" appears at the beginning of a word, both letters should be +considered within the ::first-letter pseudo-element. + +

If the letters that would form the ::first-letter are not in the +same element, such as "'T" in <p>'<em>T..., the UA +may create a ::first-letter pseudo-element from one of the elements, +both elements, or simply not create a pseudo-element.

+ +

Similarly, if the first letter(s) of the block are not at the start +of the line (for example due to bidirectional reordering), then the UA +need not create the pseudo-element(s). + +

+

Example:

+

The following example illustrates +how overlapping pseudo-elements may interact. The first letter of +each P element will be green with a font size of '24pt'. The rest of +the first formatted line will be 'blue' while the rest of the +paragraph will be 'red'.

+ +
p { color: red; font-size: 12pt }
+p::first-letter { color: green; font-size: 200% }
+p::first-line { color: blue }
+
+<P>Some text that ends up on two lines</P>
+ +

Assuming that a line break will occur before the word "ends", the +fictional tag +sequence for this fragment might be:

+ +
<P>
+<P::first-line>
+<P::first-letter> 
+S 
+</P::first-letter>ome text that 
+</P::first-line> 
+ends up on two lines 
+</P>
+ +

Note that the ::first-letter element is inside the ::first-line +element. Properties set on ::first-line are inherited by +::first-letter, but are overridden if the same property is set on +::first-letter.

+
+ + +

7.3. The ::selection pseudo-element

+ +

The ::selection pseudo-element applies to the portion +of a document that has been highlighted by the user. This also +applies, for example, to selected text within an editable text +field. This pseudo-element should not be confused with the :checked pseudo-class (which used to be +named :selected) + +

Although the ::selection pseudo-element is dynamic in +nature, and is altered by user action, it is reasonable to expect that +when a UA re-renders to a static medium (such as a printed page, see +[CSS21]) which was originally rendered to a +dynamic medium (like screen), the UA may wish to transfer the current +::selection state to that other medium, and have all the +appropriate formatting and rendering take effect as well. This is not +required — UAs may omit the ::selection +pseudo-element for static media. + +

These are the CSS properties that apply to ::selection +pseudo-elements: color, background, cursor (optional), outline +(optional). The computed value of the 'background-image' property on +::selection may be ignored. + + +

7.4. The ::before and ::after pseudo-elements

+ +

The ::before and ::after pseudo-elements +can be used to describe generated content before or after an element's +content. They are explained in CSS 2.1 [CSS21].

+ +

When the ::first-letter and ::first-line +pseudo-elements are combined with ::before and +::after, they apply to the first letter or line of the +element including the inserted text.

+ +

8. Combinators

+ +

8.1. Descendant combinator

+ +

At times, authors may want selectors to describe an element that is +the descendant of another element in the document tree (e.g., "an +EM element that is contained within an H1 +element"). Descendant combinators express such a relationship. A +descendant combinator is white space that +separates two sequences of simple selectors. A selector of the form +"A B" represents an element B that is an +arbitrary descendant of some ancestor element A. + +

+

Examples:

+

For example, consider the following selector:

+
h1 em
+

It represents an em element being the descendant of + an h1 element. It is a correct and valid, but partial, + description of the following fragment:

+
<h1>This <span class="myclass">headline
+is <em>very</em> important</span></h1>
+

The following selector:

+
div * p
+

represents a p element that is a grandchild or later + descendant of a div element. Note the whitespace on + either side of the "*" is not part of the universal selector; the + whitespace is a combinator indicating that the DIV must be the + ancestor of some element, and that that element must be an ancestor + of the P.

+

The following selector, which combines descendant combinators and + attribute selectors, represents an + element that (1) has the href attribute set and (2) is + inside a p that is itself inside a div:

+
div p *[href]
+
+ +

8.2. Child combinators

+ +

A child combinator describes a childhood relationship +between two elements. A child combinator is made of the +"greater-than sign" (>) character and +separates two sequences of simple selectors. + + +

+

Examples:

+

The following selector represents a p element that is + child of body:

+
body > p
+

The following example combines descendant combinators and child + combinators.

+
div ol>li p
+

It represents a p element that is a descendant of an + li element; the li element must be the + child of an ol element; the ol element must + be a descendant of a div. Notice that the optional white + space around the ">" combinator has been left out.

+
+ +

For information on selecting the first child of an element, please +see the section on the :first-child pseudo-class +above.

+ +

8.3. Sibling combinators

+ +

There are two different sibling combinators: the adjacent sibling +combinator and the general sibling combinator. In both cases, +non-element nodes (e.g. text between elements) are ignored when +considering adjacency of elements.

+ +

8.3.1. Adjacent sibling combinator

+ +

The adjacent sibling combinator is made of the "plus +sign" (U+002B, +) character that separates two +sequences of simple selectors. The elements represented by the two +sequences share the same parent in the document tree and the element +represented by the first sequence immediately precedes the element +represented by the second one.

+ +
+

Examples:

+

The following selector represents a p element + immediately following a math element:

+
math + p
+

The following selector is conceptually similar to the one in the + previous example, except that it adds an attribute selector — it + adds a constraint to the h1 element, that it must have + class="opener":

+
h1.opener + h2
+
+ + +

8.3.2. General sibling combinator

+ +

The general sibling combinator is made of the "tilde" +(U+007E, ~) character that separates two sequences of +simple selectors. The elements represented by the two sequences share +the same parent in the document tree and the element represented by +the first sequence precedes (not necessarily immediately) the element +represented by the second one.

+ +
+

Example:

+
h1 ~ pre
+

represents a pre element following an h1. It + is a correct and valid, but partial, description of:

+
<h1>Definition of the function a</h1>
+<p>Function a(x) has to be applied to all figures in the table.</p>
+<pre>function a(x) = 12x/13.5</pre>
+
+ +

9. Calculating a selector's specificity

+ +

A selector's specificity is calculated as follows:

+ + + +

Selectors inside the negation pseudo-class +are counted like any other, but the negation itself does not count as +a pseudo-class.

+ +

Concatenating the three numbers a-b-c (in a number system with a +large base) gives the specificity.

+ +
+

Examples:

+
*               /* a=0 b=0 c=0 -> specificity =   0 */
+LI              /* a=0 b=0 c=1 -> specificity =   1 */
+UL LI           /* a=0 b=0 c=2 -> specificity =   2 */
+UL OL+LI        /* a=0 b=0 c=3 -> specificity =   3 */
+H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity =  11 */
+UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */
+LI.red.level    /* a=0 b=2 c=1 -> specificity =  21 */
+#x34y           /* a=1 b=0 c=0 -> specificity = 100 */
+#s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 101 */
+
+
+ +

Note: the specificity of the styles +specified in an HTML style attribute is described in CSS +2.1. [CSS21].

+ +

10. The grammar of Selectors

+ +

10.1. Grammar

+ +

The grammar below defines the syntax of Selectors. It is globally +LL(1) and can be locally LL(2) (but note that most UA's should not use +it directly, since it doesn't express the parsing conventions). The +format of the productions is optimized for human consumption and some +shorthand notations beyond Yacc (see [YACC]) +are used:

+ + + +

The productions are:

+ +
selectors_group
+  : selector [ COMMA S* selector ]*
+  ;
+
+selector
+  : simple_selector_sequence [ combinator simple_selector_sequence ]*
+  ;
+
+combinator
+  /* combinators can be surrounded by white space */
+  : PLUS S* | GREATER S* | TILDE S* | S+
+  ;
+
+simple_selector_sequence
+  : [ type_selector | universal ]
+    [ HASH | class | attrib | pseudo | negation ]*
+  | [ HASH | class | attrib | pseudo | negation ]+
+  ;
+
+type_selector
+  : [ namespace_prefix ]? element_name
+  ;
+
+namespace_prefix
+  : [ IDENT | '*' ]? '|'
+  ;
+
+element_name
+  : IDENT
+  ;
+
+universal
+  : [ namespace_prefix ]? '*'
+  ;
+
+class
+  : '.' IDENT
+  ;
+
+attrib
+  : '[' S* [ namespace_prefix ]? IDENT S*
+        [ [ PREFIXMATCH |
+            SUFFIXMATCH |
+            SUBSTRINGMATCH |
+            '=' |
+            INCLUDES |
+            DASHMATCH ] S* [ IDENT | STRING ] S*
+        ]? ']'
+  ;
+
+pseudo
+  /* '::' starts a pseudo-element, ':' a pseudo-class */
+  /* Exceptions: :first-line, :first-letter, :before and :after. */
+  /* Note that pseudo-elements are restricted to one per selector and */
+  /* occur only in the last simple_selector_sequence. */
+  : ':' ':'? [ IDENT | functional_pseudo ]
+  ;
+
+functional_pseudo
+  : FUNCTION S* expression ')'
+  ;
+
+expression
+  /* In CSS3, the expressions are identifiers, strings, */
+  /* or of the form "an+b" */
+  : [ [ PLUS | '-' | DIMENSION | NUMBER | STRING | IDENT ] S* ]+
+  ;
+
+negation
+  : NOT S* negation_arg S* ')'
+  ;
+
+negation_arg
+  : type_selector | universal | HASH | class | attrib | pseudo
+  ;
+ + +

10.2. Lexical scanner

+ +

The following is the tokenizer, written in Flex (see +[FLEX]) notation. The tokenizer is +case-insensitive.

+ +

The two occurrences of "\377" represent the highest character +number that current versions of Flex can deal with (decimal 255). They +should be read as "\4177777" (decimal 1114111), which is the highest +possible code point in Unicode/ISO-10646. [UNICODE]

+ +
%option case-insensitive
+
+ident     [-]?{nmstart}{nmchar}*
+name      {nmchar}+
+nmstart   [_a-z]|{nonascii}|{escape}
+nonascii  [^\0-\177]
+unicode   \\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?
+escape    {unicode}|\\[^\n\r\f0-9a-f]
+nmchar    [_a-z0-9-]|{nonascii}|{escape}
+num       [0-9]+|[0-9]*\.[0-9]+
+string    {string1}|{string2}
+string1   \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*\"
+string2   \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*\'
+invalid   {invalid1}|{invalid2}
+invalid1  \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*
+invalid2  \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*
+nl        \n|\r\n|\r|\f
+w         [ \t\r\n\f]*
+
+%%
+
+[ \t\r\n\f]+     return S;
+
+"~="             return INCLUDES;
+"|="             return DASHMATCH;
+"^="             return PREFIXMATCH;
+"$="             return SUFFIXMATCH;
+"*="             return SUBSTRINGMATCH;
+{ident}          return IDENT;
+{string}         return STRING;
+{ident}"("       return FUNCTION;
+{num}            return NUMBER;
+"#"{name}        return HASH;
+{w}"+"           return PLUS;
+{w}">"           return GREATER;
+{w}","           return COMMA;
+{w}"~"           return TILDE;
+":not("          return NOT;
+@{ident}         return ATKEYWORD;
+{invalid}        return INVALID;
+{num}%           return PERCENTAGE;
+{num}{ident}     return DIMENSION;
+"<!--"           return CDO;
+"-->"            return CDC;
+
+"url("{w}{string}{w}")"                           return URI;
+"url("{w}([!#$%&*-~]|{nonascii}|{escape})*{w}")"  return URI;
+U\+[0-9a-f?]{1,6}(-[0-9a-f]{1,6})?                return UNICODE_RANGE;
+
+\/\*[^*]*\*+([^/*][^*]*\*+)*\/                    /* ignore comments */
+
+.                return *yytext;
+ + + +

11. Namespaces and down-level clients

+ +

An important issue is the interaction of CSS selectors with XML +documents in web clients that were produced prior to this +document. Unfortunately, due to the fact that namespaces must be +matched based on the URI which identifies the namespace, not the +namespace prefix, some mechanism is required to identify namespaces in +CSS by their URI as well. Without such a mechanism, it is impossible +to construct a CSS style sheet which will properly match selectors in +all cases against a random set of XML documents. However, given +complete knowledge of the XML document to which a style sheet is to be +applied, and a limited use of namespaces within the XML document, it +is possible to construct a style sheet in which selectors would match +elements and attributes correctly.

+ +

It should be noted that a down-level CSS client will (if it +properly conforms to CSS forward compatible parsing rules) ignore all +@namespace at-rules, as well as all style rules that make +use of namespace qualified element type or attribute selectors. The +syntax of delimiting namespace prefixes in CSS was deliberately chosen +so that down-level CSS clients would ignore the style rules rather +than possibly match them incorrectly.

+ +

The use of default namespaces in CSS makes it possible to write +element type selectors that will function in both namespace aware CSS +clients as well as down-level clients. It should be noted that +down-level clients may incorrectly match selectors against XML +elements in other namespaces.

+ +

The following are scenarios and examples in which it is possible to +construct style sheets which would function properly in web clients +that do not implement this proposal.

+ +
    +
  1. + +

    The XML document does not use namespaces.

    + +
      + +
    • In this case, it is obviously not necessary to declare or use + namespaces in the style sheet. Standard CSS element type and + attribute selectors will function adequately in a down-level + client.
    • + +
    • In a CSS namespace aware client, the default behavior of + element selectors matching without regard to namespace will + function properly against all elements, since no namespaces are + present. However, the use of specific element type selectors that + match only elements that have no namespace ("|name") + will guarantee that selectors will match only XML elements that do + not have a declared namespace.
    • + +
    + +
  2. + +
  3. + +

    The XML document defines a single, default namespace used + throughout the document. No namespace prefixes are used in element + names.

    + +
      + +
    • In this case, a down-level client will function as if + namespaces were not used in the XML document at all. Standard CSS + element type and attribute selectors will match against all + elements.
    • + +
    + +
  4. + +
  5. + +

    The XML document does not use a default namespace, all + namespace prefixes used are known to the style sheet author, and + there is a direct mapping between namespace prefixes and namespace + URIs. (A given prefix may only be mapped to one namespace URI + throughout the XML document; there may be multiple prefixes mapped + to the same URI).

    + +
      + +
    • In this case, the down-level client will view and match + element type and attribute selectors based on their fully + qualified name, not the local part as outlined in the Type selectors and Namespaces section. CSS + selectors may be declared using an escaped colon "\:" + to describe the fully qualified names, e.g. + "html\:h1" will match + <html:h1>. Selectors using the qualified name + will only match XML elements that use the same prefix. Other + namespace prefixes used in the XML that are mapped to the same URI + will not match as expected unless additional CSS style rules are + declared for them.
    • + +
    • Note that selectors declared in this fashion will + only match in down-level clients. A CSS namespace aware + client will match element type and attribute selectors based on + the name's local part. Selectors declared with the fully + qualified name will not match (unless there is no namespace prefix + in the fully qualified name).
    • + +
    + +
  6. + +
+ +

In other scenarios: when the namespace prefixes used in the XML are +not known in advance by the style sheet author; or a combination of +elements with no namespace are used in conjunction with elements using +a default namespace; or the same namespace prefix is mapped to +different namespace URIs within the same document, or in +different documents; it is impossible to construct a CSS style sheet +that will function properly against all elements in those documents, +unless, the style sheet is written using a namespace URI syntax (as +outlined in this document or similar) and the document is processed by +a CSS and XML namespace aware client.

+ +

12. Profiles

+ +

Each specification using Selectors must define the subset of W3C +Selectors it allows and excludes, and describe the local meaning of +all the components of that subset.

+ +

Non normative examples: + +

+ + + + + + + + + + + + + + + +
Selectors profile
SpecificationCSS level 1
Acceptstype selectors
class selectors
ID selectors
:link, + :visited and :active pseudo-classes
descendant combinator +
::first-line and ::first-letter pseudo-elements
Excludes + +

universal selector
attribute selectors
:hover and :focus + pseudo-classes
:target pseudo-class
:lang() pseudo-class
all UI + element states pseudo-classes
all structural + pseudo-classes
negation pseudo-class
all + UI element fragments pseudo-elements
::before and ::after + pseudo-elements
child combinators
sibling combinators + +

namespaces

Extra constraintsonly one class selector allowed per sequence of simple + selectors


+ + + + + + + + + + + + + + + +
Selectors profile
SpecificationCSS level 2
Acceptstype selectors
universal selector
attribute presence and + values selectors
class selectors
ID selectors
:link, :visited, + :active, :hover, :focus, :lang() and :first-child pseudo-classes +
descendant combinator
child combinator
adjacent sibling + combinator
::first-line and ::first-letter pseudo-elements
::before + and ::after pseudo-elements
Excludes + +

content selectors
substring matching attribute + selectors
:target pseudo-classes
all UI element + states pseudo-classes
all structural pseudo-classes other + than :first-child
negation pseudo-class
all UI element + fragments pseudo-elements
general sibling combinators + +

namespaces

Extra constraintsmore than one class selector per sequence of simple selectors (CSS1 + constraint) allowed
+ +

In CSS, selectors express pattern matching rules that determine which style +rules apply to elements in the document tree. + +

The following selector (CSS level 2) will match all anchors a +with attribute name set inside a section 1 header h1: +

h1 a[name]
+ +

All CSS declarations attached to such a selector are applied to elements +matching it.

+ +
+ + + + + + + + + + + + + + + + +
Selectors profile
SpecificationSTTS 3
Accepts + +

type selectors
universal selectors
attribute selectors
class + selectors
ID selectors
all structural pseudo-classes
+ all combinators + +

namespaces

Excludesnon-accepted pseudo-classes
pseudo-elements
Extra constraintssome selectors and combinators are not allowed in fragment + descriptions on the right side of STTS declarations.
+ +

Selectors can be used in STTS 3 in two different + manners: +

    +
  1. a selection mechanism equivalent to CSS selection mechanism: declarations + attached to a given selector are applied to elements matching that selector, +
  2. fragment descriptions that appear on the right side of declarations. +
+ +

13. Conformance and requirements

+ +

This section defines conformance with the present specification only. + +

The inability of a user agent to implement part of this specification due to +the limitations of a particular device (e.g., non interactive user agents will +probably not implement dynamic pseudo-classes because they make no sense without +interactivity) does not imply non-conformance. + +

All specifications reusing Selectors must contain a Profile listing the +subset of Selectors it accepts or excludes, and describing the constraints +it adds to the current specification. + +

Invalidity is caused by a parsing error, e.g. an unrecognized token or a token +which is not allowed at the current parsing point. + +

User agents must observe the rules for handling parsing errors: +

+ +

Specifications reusing Selectors must define how to handle parsing +errors. (In the case of CSS, the entire rule in which the selector is +used is dropped.)

+ + + +

14. Tests

+ +

This specification has a test +suite allowing user agents to verify their basic conformance to +the specification. This test suite does not pretend to be exhaustive +and does not cover all possible combined cases of Selectors.

+ +

15. Acknowledgements

+ +

The CSS working group would like to thank everyone who has sent +comments on this specification over the years.

+ +

The working group would like to extend special thanks to Donna +McManus, Justin Baker, Joel Sklar, and Molly Ives Brower who perfermed +the final editorial review.

+ +

16. References

+ +
+ +
[CSS1] +
Bert Bos, Håkon Wium Lie; "Cascading Style Sheets, level 1", W3C Recommendation, 17 Dec 1996, revised 11 Jan 1999 +
(http://www.w3.org/TR/REC-CSS1) + +
[CSS21] +
Bert Bos, Tantek Çelik, Ian Hickson, Håkon Wium Lie, editors; "Cascading Style Sheets, level 2 revision 1", W3C Working Draft, 13 June 2005 +
(http://www.w3.org/TR/CSS21) + +
[CWWW] +
Martin J. Dürst, François Yergeau, Misha Wolf, Asmus Freytag, Tex Texin, editors; "Character Model for the World Wide Web", W3C Recommendation, 15 February 2005 +
(http://www.w3.org/TR/charmod/) + +
[FLEX] +
"Flex: The Lexical Scanner Generator", Version 2.3.7, ISBN 1882114213 + +
[HTML4] +
Dave Ragget, Arnaud Le Hors, Ian Jacobs, editors; "HTML 4.01 Specification", W3C Recommendation, 24 December 1999 +
(http://www.w3.org/TR/html4/) + +
[MATH] +
Patrick Ion, Robert Miner, editors; "Mathematical Markup Language (MathML) 1.01", W3C Recommendation, revision of 7 July 1999 +
(http://www.w3.org/TR/REC-MathML/) + +
[RFC3066] +
H. Alvestrand; "Tags for the Identification of Languages", Request for Comments 3066, January 2001 +
(http://www.ietf.org/rfc/rfc3066.txt) + +
[STTS] +
Daniel Glazman; "Simple Tree Transformation Sheets 3", Electricité de France, submission to the W3C, 11 November 1998 +
(http://www.w3.org/TR/NOTE-STTS3) + +
[SVG] +
Jon Ferraiolo, 藤沢 淳, Dean Jackson, editors; "Scalable Vector Graphics (SVG) 1.1 Specification", W3C Recommendation, 14 January 2003 +
(http://www.w3.org/TR/SVG/) + +
[UNICODE]
+
The Unicode Standard, Version 4.1, The Unicode Consortium. Boston, MA, Addison-Wesley, March 2005. ISBN 0-321-18578-1, as amended by Unicode 4.0.1 and Unicode 4.1.0. +
(http://www.unicode.org/versions/)
+ +
[XML10] +
Tim Bray, Jean Paoli, C. M. Sperberg-McQueen, Eve Maler, François Yergeau, editors; "Extensible Markup Language (XML) 1.0 (Third Edition)", W3C Recommendation, 4 February 2004 +
(http://www.w3.org/TR/REC-xml/) + +
[XMLNAMES] +
Tim Bray, Dave Hollander, Andrew Layman, editors; "Namespaces in XML", W3C Recommendation, 14 January 1999 +
(http://www.w3.org/TR/REC-xml-names/) + +
[YACC] +
S. C. Johnson; "YACC — Yet another compiler compiler", Technical Report, Murray Hill, 1975 + +
+ +
+ test +
+
+
+ test +
+ test +
+
+
+ test +
+
+
+
+ +
+ d1d1 + d2d2 + d3d3 + d4d4 + d5d5 + d6d6 + + + + + + +
+
+ d1 + d1 + + d2 + d2 + + d3 + d3 + + d4 + d4 + + d5 + d5 + + d6 + d6 + +
+ + + diff --git a/test_new/browser/fixtures/slick/template-chromeframe.html b/test_new/browser/fixtures/slick/template-chromeframe.html new file mode 100644 index 0000000..815a193 --- /dev/null +++ b/test_new/browser/fixtures/slick/template-chromeframe.html @@ -0,0 +1,2932 @@ + + + + + + + + template xhtml as html + + + +
+

W3C + +

Selectors

+ +

W3C Working Draft 15 December 2005

+ +
+ +
This version: + +
+ http://www.w3.org/TR/2005/WD-css3-selectors-20051215 + +
Latest version: + +
+ http://www.w3.org/TR/css3-selectors + +
Previous version: + +
+ http://www.w3.org/TR/2001/CR-css3-selectors-20011113 + +
Editors: + +
Daniel Glazman (Invited Expert)
+ +
Tantek Çelik (Invited Expert) + +
Ian Hickson (Google) + +
Peter Linss (former editor, Netscape/AOL) + +
John Williams (former editor, Quark, Inc.) + +
+ +
+ +
+ +

Abstract

+ +

Selectors are patterns that match against elements in a + tree. Selectors have been optimized for use with HTML and XML, and + are designed to be usable in performance-critical code.

+ +

CSS (Cascading + Style Sheets) is a language for describing the rendering of HTML and XML documents on + screen, on paper, in speech, etc. CSS uses Selectors for binding + style properties to elements in the document. This document + describes extensions to the selectors defined in CSS level 2. These + extended selectors will be used by CSS level 3. + +

Selectors define the following function:

+ +
expression ∗ element → boolean
+ +

That is, given an element and a selector, this specification + defines whether that element matches the selector.

+ +

These expressions can also be used, for instance, to select a set + of elements, or a single element from a set of elements, by + evaluating the expression across all the elements in a + subtree. STTS (Simple Tree Transformation Sheets), a + language for transforming XML trees, uses this mechanism. [STTS]

+ +

Status of this document

+ +

This section describes the status of this document at the + time of its publication. Other documents may supersede this + document. A list of current W3C publications and the latest revision + of this technical report can be found in the W3C technical reports index at + http://www.w3.org/TR/.

+ +

This document describes the selectors that already exist in CSS1 and CSS2, and + also proposes new selectors for CSS3 and other languages that may need them.

+ +

The CSS Working Group doesn't expect that all implementations of + CSS3 will have to implement all selectors. Instead, there will + probably be a small number of variants of CSS3, called profiles. For + example, it may be that only a profile for interactive user agents + will include all of the selectors.

+ +

This specification is a last call working draft for the the CSS Working Group + (Style Activity). This + document is a revision of the Candidate + Recommendation dated 2001 November 13, and has incorporated + implementation feedback received in the past few years. It is + expected that this last call will proceed straight to Proposed + Recommendation stage since it is believed that interoperability will + be demonstrable.

+ +

All persons are encouraged to review and implement this + specification and return comments to the (archived) + public mailing list www-style + (see instructions). W3C + Members can also send comments directly to the CSS Working + Group. + The deadline for comments is 14 January 2006.

+ +

This is still a draft document and may be updated, replaced, or + obsoleted by other documents at any time. It is inappropriate to + cite a W3C Working Draft as other than "work in progress". + +

This document may be available in translation. + The English version of this specification is the only normative + version. + +

+ +

Table of contents

+ + + +
+ +

1. Introduction

+ +

1.1. Dependencies

+ +

Some features of this specification are specific to CSS, or have + particular limitations or rules specific to CSS. In this + specification, these have been described in terms of CSS2.1. [CSS21]

+ +

1.2. Terminology

+ +

All of the text of this specification is normative except + examples, notes, and sections explicitly marked as + non-normative.

+ +

1.3. Changes from CSS2

+ +

This section is non-normative.

+ +

The main differences between the selectors in CSS2 and those in + Selectors are: + +

+ +

2. Selectors

+ +

This section is non-normative, as it merely summarizes the +following sections.

+ +

A Selector represents a structure. This structure can be used as a +condition (e.g. in a CSS rule) that determines which elements a +selector matches in the document tree, or as a flat description of the +HTML or XML fragment corresponding to that structure.

+ +

Selectors may range from simple element names to rich contextual +representations.

+ +

The following table summarizes the Selector syntax:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PatternMeaningDescribed in sectionFirst defined in CSS level
*any elementUniversal + selector2
Ean element of type EType selector1
E[foo]an E element with a "foo" attributeAttribute + selectors2
E[foo="bar"]an E element whose "foo" attribute value is exactly + equal to "bar"Attribute + selectors2
E[foo~="bar"]an E element whose "foo" attribute value is a list of + space-separated values, one of which is exactly equal to "bar"Attribute + selectors2
E[foo^="bar"]an E element whose "foo" attribute value begins exactly + with the string "bar"Attribute + selectors3
E[foo$="bar"]an E element whose "foo" attribute value ends exactly + with the string "bar"Attribute + selectors3
E[foo*="bar"]an E element whose "foo" attribute value contains the + substring "bar"Attribute + selectors3
E[hreflang|="en"]an E element whose "hreflang" attribute has a hyphen-separated + list of values beginning (from the left) with "en"Attribute + selectors2
E:rootan E element, root of the documentStructural + pseudo-classes3
E:nth-child(n)an E element, the n-th child of its parentStructural + pseudo-classes3
E:nth-last-child(n)an E element, the n-th child of its parent, counting + from the last oneStructural + pseudo-classes3
E:nth-of-type(n)an E element, the n-th sibling of its typeStructural + pseudo-classes3
E:nth-last-of-type(n)an E element, the n-th sibling of its type, counting + from the last oneStructural + pseudo-classes3
E:first-childan E element, first child of its parentStructural + pseudo-classes2
E:last-childan E element, last child of its parentStructural + pseudo-classes3
E:first-of-typean E element, first sibling of its typeStructural + pseudo-classes3
E:last-of-typean E element, last sibling of its typeStructural + pseudo-classes3
E:only-childan E element, only child of its parentStructural + pseudo-classes3
E:only-of-typean E element, only sibling of its typeStructural + pseudo-classes3
E:emptyan E element that has no children (including text + nodes)Structural + pseudo-classes3
E:link
E:visited
an E element being the source anchor of a hyperlink of + which the target is not yet visited (:link) or already visited + (:visited)The link + pseudo-classes1
E:active
E:hover
E:focus
an E element during certain user actionsThe user + action pseudo-classes1 and 2
E:targetan E element being the target of the referring URIThe target + pseudo-class3
E:lang(fr)an element of type E in language "fr" (the document + language specifies how language is determined)The :lang() + pseudo-class2
E:enabled
E:disabled
a user interface element E which is enabled or + disabledThe UI element states + pseudo-classes3
E:checkeda user interface element E which is checked (for instance a radio-button or checkbox)The UI element states + pseudo-classes3
E::first-linethe first formatted line of an E elementThe ::first-line + pseudo-element1
E::first-letterthe first formatted letter of an E elementThe ::first-letter + pseudo-element1
E::selectionthe portion of an E element that is currently + selected/highlighted by the userThe UI element + fragments pseudo-elements3
E::beforegenerated content before an E elementThe ::before + pseudo-element2
E::aftergenerated content after an E elementThe ::after + pseudo-element2
E.warningan E element whose class is +"warning" (the document language specifies how class is determined).Class + selectors1
E#myidan E element with ID equal to "myid".ID + selectors1
E:not(s)an E element that does not match simple selector sNegation + pseudo-class3
E Fan F element descendant of an E elementDescendant + combinator1
E > Fan F element child of an E elementChild + combinator2
E + Fan F element immediately preceded by an E elementAdjacent sibling combinator2
E ~ Fan F element preceded by an E elementGeneral sibling combinator3
+ +

The meaning of each selector is derived from the table above by +prepending "matches" to the contents of each cell in the "Meaning" +column.

+ +

3. Case sensitivity

+ +

The case sensitivity of document language element names, attribute +names, and attribute values in selectors depends on the document +language. For example, in HTML, element names are case-insensitive, +but in XML, they are case-sensitive.

+ +

4. Selector syntax

+ +

A selector is a chain of one +or more sequences of simple selectors +separated by combinators.

+ +

A sequence of simple selectors +is a chain of simple selectors +that are not separated by a combinator. It +always begins with a type selector or a +universal selector. No other type +selector or universal selector is allowed in the sequence.

+ +

A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, content selector, or pseudo-class. One pseudo-element may be appended to the last +sequence of simple selectors.

+ +

Combinators are: white space, "greater-than +sign" (U+003E, >), "plus sign" (U+002B, ++) and "tilde" (U+007E, ~). White +space may appear between a combinator and the simple selectors around +it. Only the characters "space" (U+0020), "tab" +(U+0009), "line feed" (U+000A), "carriage return" (U+000D), and "form +feed" (U+000C) can occur in white space. Other space-like characters, +such as "em-space" (U+2003) and "ideographic space" (U+3000), are +never part of white space.

+ +

The elements of a document tree that are represented by a selector +are the subjects of the selector. A +selector consisting of a single sequence of simple selectors +represents any element satisfying its requirements. Prepending another +sequence of simple selectors and a combinator to a sequence imposes +additional matching constraints, so the subjects of a selector are +always a subset of the elements represented by the last sequence of +simple selectors.

+ +

An empty selector, containing no sequence of simple selectors and +no pseudo-element, is an invalid +selector.

+ +

5. Groups of selectors

+ +

When several selectors share the same declarations, they may be +grouped into a comma-separated list. (A comma is U+002C.)

+ +
+

CSS examples:

+

In this example, we condense three rules with identical +declarations into one. Thus,

+
h1 { font-family: sans-serif }
+h2 { font-family: sans-serif }
+h3 { font-family: sans-serif }
+

is equivalent to:

+
h1, h2, h3 { font-family: sans-serif }
+
+ +

Warning: the equivalence is true in this example +because all the selectors are valid selectors. If just one of these +selectors were invalid, the entire group of selectors would be +invalid. This would invalidate the rule for all three heading +elements, whereas in the former case only one of the three individual +heading rules would be invalidated.

+ + +

6. Simple selectors

+ +

6.1. Type selector

+ +

A type selector is the name of a document language +element type. A type selector represents an instance of the element +type in the document tree.

+ +
+

Example:

+

The following selector represents an h1 element in the document tree:

+
h1
+
+ + +

6.1.1. Type selectors and namespaces

+ +

Type selectors allow an optional namespace ([XMLNAMES]) component. A namespace prefix +that has been previously declared may be prepended to the element name +separated by the namespace separator "vertical bar" +(U+007C, |).

+ +

The namespace component may be left empty to indicate that the +selector is only to represent elements with no declared namespace.

+ +

An asterisk may be used for the namespace prefix, indicating that +the selector represents elements in any namespace (including elements +with no namespace).

+ +

Element type selectors that have no namespace component (no +namespace separator), represent elements without regard to the +element's namespace (equivalent to "*|") unless a default +namespace has been declared. If a default namespace has been declared, +the selector will represent only elements in the default +namespace.

+ +

A type selector containing a namespace prefix that has not been +previously declared is an invalid selector. +The mechanism for declaring a namespace prefix is left up to the +language implementing Selectors. In CSS, such a mechanism is defined +in the General Syntax module.

+ +

In a namespace-aware client, element type selectors will only match +against the local part +of the element's qualified +name. See below for notes about matching +behaviors in down-level clients.

+ +

In summary:

+ +
+
ns|E
+
elements with name E in namespace ns
+
*|E
+
elements with name E in any namespace, including those without any + declared namespace
+
|E
+
elements with name E without any declared namespace
+
E
+
if no default namespace has been specified, this is equivalent to *|E. + Otherwise it is equivalent to ns|E where ns is the default namespace.
+
+ +
+

CSS examples:

+ +
@namespace foo url(http://www.example.com);
+ foo|h1 { color: blue }
+ foo|* { color: yellow }
+ |h1 { color: red }
+ *|h1 { color: green }
+ h1 { color: green }
+ +

The first rule will match only h1 elements in the + "http://www.example.com" namespace.

+ +

The second rule will match all elements in the + "http://www.example.com" namespace.

+ +

The third rule will match only h1 elements without + any declared namespace.

+ +

The fourth rule will match h1 elements in any + namespace (including those without any declared namespace).

+ +

The last rule is equivalent to the fourth rule because no default + namespace has been defined.

+ +
+ +

6.2. Universal selector

+ +

The universal selector, written "asterisk" +(*), represents the qualified name of any element +type. It represents any single element in the document tree in any +namespace (including those without any declared namespace) if no +default namespace has been specified. If a default namespace has been +specified, see Universal selector and +Namespaces below.

+ +

If the universal selector is not the only component of a sequence +of simple selectors, the * may be omitted.

+ +
+

Examples:

+
    +
  • *[hreflang|=en] and [hreflang|=en] are equivalent,
  • +
  • *.warning and .warning are equivalent,
  • +
  • *#myid and #myid are equivalent.
  • +
+
+ +

Note: it is recommended that the +*, representing the universal selector, not be +omitted.

+ +

6.2.1. Universal selector and namespaces

+ +

The universal selector allows an optional namespace component. It +is used as follows:

+ +
+
ns|*
+
all elements in namespace ns
+
*|*
+
all elements
+
|*
+
all elements without any declared namespace
+
*
+
if no default namespace has been specified, this is equivalent to *|*. + Otherwise it is equivalent to ns|* where ns is the default namespace.
+
+ +

A universal selector containing a namespace prefix that has not +been previously declared is an invalid +selector. The mechanism for declaring a namespace prefix is left up +to the language implementing Selectors. In CSS, such a mechanism is +defined in the General Syntax module.

+ + +

6.3. Attribute selectors

+ +

Selectors allow the representation of an element's attributes. When +a selector is used as an expression to match against an element, +attribute selectors must be considered to match an element if that +element has an attribute that matches the attribute represented by the +attribute selector.

+ +

6.3.1. Attribute presence and values +selectors

+ +

CSS2 introduced four attribute selectors:

+ +
+
[att] +
Represents an element with the att attribute, whatever the value of + the attribute.
+
[att=val]
+
Represents an element with the att attribute whose value is exactly + "val".
+
[att~=val]
+
Represents an element with the att attribute whose value is a whitespace-separated list of words, one of + which is exactly "val". If "val" contains whitespace, it will never + represent anything (since the words are separated by + spaces).
+
[att|=val] +
Represents an element with the att attribute, its value either + being exactly "val" or beginning with "val" immediately followed by + "-" (U+002D). This is primarily intended to allow language subcode + matches (e.g., the hreflang attribute on the + link element in HTML) as described in RFC 3066 ([RFC3066]). For lang (or + xml:lang) language subcode matching, please see the :lang pseudo-class.
+
+ +

Attribute values must be identifiers or strings. The +case-sensitivity of attribute names and values in selectors depends on +the document language.

+ +
+ +

Examples:

+ +

The following attribute selector represents an h1 + element that carries the title attribute, whatever its + value:

+ +
h1[title]
+ +

In the following example, the selector represents a + span element whose class attribute has + exactly the value "example":

+ +
span[class="example"]
+ +

Multiple attribute selectors can be used to represent several + attributes of an element, or several conditions on the same + attribute. Here, the selector represents a span element + whose hello attribute has exactly the value "Cleveland" + and whose goodbye attribute has exactly the value + "Columbus":

+ +
span[hello="Cleveland"][goodbye="Columbus"]
+ +

The following selectors illustrate the differences between "=" + and "~=". The first selector will represent, for example, the value + "copyright copyleft copyeditor" on a rel attribute. The + second selector will only represent an a element with + an href attribute having the exact value + "http://www.w3.org/".

+ +
a[rel~="copyright"]
+a[href="http://www.w3.org/"]
+ +

The following selector represents a link element + whose hreflang attribute is exactly "fr".

+ +
link[hreflang=fr]
+ +

The following selector represents a link element for + which the values of the hreflang attribute begins with + "en", including "en", "en-US", and "en-cockney":

+ +
link[hreflang|="en"]
+ +

Similarly, the following selectors represents a + DIALOGUE element whenever it has one of two different + values for an attribute character:

+ +
DIALOGUE[character=romeo]
+DIALOGUE[character=juliet]
+ +
+ +

6.3.2. Substring matching attribute +selectors

+ +

Three additional attribute selectors are provided for matching +substrings in the value of an attribute:

+ +
+
[att^=val]
+
Represents an element with the att attribute whose value begins + with the prefix "val".
+
[att$=val] +
Represents an element with the att attribute whose value ends with + the suffix "val".
+
[att*=val] +
Represents an element with the att attribute whose value contains + at least one instance of the substring "val".
+
+ +

Attribute values must be identifiers or strings. The +case-sensitivity of attribute names in selectors depends on the +document language.

+ +
+

Examples:

+

The following selector represents an HTML object, referencing an + image:

+
object[type^="image/"]
+

The following selector represents an HTML anchor a with an + href attribute whose value ends with ".html".

+
a[href$=".html"]
+

The following selector represents an HTML paragraph with a title + attribute whose value contains the substring "hello"

+
p[title*="hello"]
+
+ +

6.3.3. Attribute selectors and namespaces

+ +

Attribute selectors allow an optional namespace component to the +attribute name. A namespace prefix that has been previously declared +may be prepended to the attribute name separated by the namespace +separator "vertical bar" (|). In keeping with +the Namespaces in the XML recommendation, default namespaces do not +apply to attributes, therefore attribute selectors without a namespace +component apply only to attributes that have no declared namespace +(equivalent to "|attr"). An asterisk may be used for the +namespace prefix indicating that the selector is to match all +attribute names without regard to the attribute's namespace. + +

An attribute selector with an attribute name containing a namespace +prefix that has not been previously declared is an invalid selector. The mechanism for declaring +a namespace prefix is left up to the language implementing Selectors. +In CSS, such a mechanism is defined in the General Syntax module. + +

+

CSS examples:

+
@namespace foo "http://www.example.com";
+[foo|att=val] { color: blue }
+[*|att] { color: yellow }
+[|att] { color: green }
+[att] { color: green }
+ +

The first rule will match only elements with the attribute + att in the "http://www.example.com" namespace with the + value "val".

+ +

The second rule will match only elements with the attribute + att regardless of the namespace of the attribute + (including no declared namespace).

+ +

The last two rules are equivalent and will match only elements + with the attribute att where the attribute is not + declared to be in a namespace.

+ +
+ +

6.3.4. Default attribute values in DTDs

+ +

Attribute selectors represent explicitly set attribute values in +the document tree. Default attribute values may be defined in a DTD or +elsewhere, but cannot always be selected by attribute +selectors. Selectors should be designed so that they work even if the +default values are not included in the document tree.

+ +

More precisely, a UA is not required to read an "external +subset" of the DTD but is required to look for default +attribute values in the document's "internal subset." (See [XML10] for definitions of these subsets.)

+ +

A UA that recognizes an XML namespace [XMLNAMES] is not required to use its +knowledge of that namespace to treat default attribute values as if +they were present in the document. (For example, an XHTML UA is not +required to use its built-in knowledge of the XHTML DTD.)

+ +

Note: Typically, implementations +choose to ignore external subsets.

+ +
+

Example:

+ +

Consider an element EXAMPLE with an attribute "notation" that has a +default value of "decimal". The DTD fragment might be

+ +
<!ATTLIST EXAMPLE notation (decimal,octal) "decimal">
+ +

If the style sheet contains the rules

+ +
EXAMPLE[notation=decimal] { /*... default property settings ...*/ }
+EXAMPLE[notation=octal]   { /*... other settings...*/ }
+ +

the first rule will not match elements whose "notation" attribute +is set by default, i.e. not set explicitly. To catch all cases, the +attribute selector for the default value must be dropped:

+ +
EXAMPLE                   { /*... default property settings ...*/ }
+EXAMPLE[notation=octal]   { /*... other settings...*/ }
+ +

Here, because the selector EXAMPLE[notation=octal] is +more specific than the tag +selector alone, the style declarations in the second rule will override +those in the first for elements that have a "notation" attribute value +of "octal". Care has to be taken that all property declarations that +are to apply only to the default case are overridden in the non-default +cases' style rules.

+ +
+ +

6.4. Class selectors

+ +

Working with HTML, authors may use the period (U+002E, +.) notation as an alternative to the ~= +notation when representing the class attribute. Thus, for +HTML, div.value and div[class~=value] have +the same meaning. The attribute value must immediately follow the +"period" (.).

+ +

UAs may apply selectors using the period (.) notation in XML +documents if the UA has namespace-specific knowledge that allows it to +determine which attribute is the "class" attribute for the +respective namespace. One such example of namespace-specific knowledge +is the prose in the specification for a particular namespace (e.g. SVG +1.0 [SVG] describes the SVG +"class" attribute and how a UA should interpret it, and +similarly MathML 1.01 [MATH] describes the MathML +"class" attribute.)

+ +
+

CSS examples:

+ +

We can assign style information to all elements with + class~="pastoral" as follows:

+ +
*.pastoral { color: green }  /* all elements with class~=pastoral */
+ +

or just

+ +
.pastoral { color: green }  /* all elements with class~=pastoral */
+ +

The following assigns style only to H1 elements with + class~="pastoral":

+ +
H1.pastoral { color: green }  /* H1 elements with class~=pastoral */
+ +

Given these rules, the first H1 instance below would not have + green text, while the second would:

+ +
<H1>Not green</H1>
+<H1 class="pastoral">Very green</H1>
+ +
+ +

To represent a subset of "class" values, each value must be preceded +by a ".", in any order.

+ +
+ +

CSS example:

+ +

The following rule matches any P element whose "class" attribute + has been assigned a list of whitespace-separated values that includes + "pastoral" and "marine":

+ +
p.pastoral.marine { color: green }
+ +

This rule matches when class="pastoral blue aqua + marine" but does not match for class="pastoral + blue".

+ +
+ +

Note: Because CSS gives considerable +power to the "class" attribute, authors could conceivably design their +own "document language" based on elements with almost no associated +presentation (such as DIV and SPAN in HTML) and assigning style +information through the "class" attribute. Authors should avoid this +practice since the structural elements of a document language often +have recognized and accepted meanings and author-defined classes may +not.

+ +

Note: If an element has multiple +class attributes, their values must be concatenated with spaces +between the values before searching for the class. As of this time the +working group is not aware of any manner in which this situation can +be reached, however, so this behavior is explicitly non-normative in +this specification.

+ +

6.5. ID selectors

+ +

Document languages may contain attributes that are declared to be +of type ID. What makes attributes of type ID special is that no two +such attributes can have the same value in a document, regardless of +the type of the elements that carry them; whatever the document +language, an ID typed attribute can be used to uniquely identify its +element. In HTML all ID attributes are named "id"; XML applications +may name ID attributes differently, but the same restriction +applies.

+ +

An ID-typed attribute of a document language allows authors to +assign an identifier to one element instance in the document tree. W3C +ID selectors represent an element instance based on its identifier. An +ID selector contains a "number sign" (U+0023, +#) immediately followed by the ID value, which must be an +identifier.

+ +

Selectors does not specify how a UA knows the ID-typed attribute of +an element. The UA may, e.g., read a document's DTD, have the +information hard-coded or ask the user. + +

+

Examples:

+

The following ID selector represents an h1 element + whose ID-typed attribute has the value "chapter1":

+
h1#chapter1
+

The following ID selector represents any element whose ID-typed + attribute has the value "chapter1":

+
#chapter1
+

The following selector represents any element whose ID-typed + attribute has the value "z98y".

+
*#z98y
+
+ +

Note. In XML 1.0 [XML10], the information about which attribute +contains an element's IDs is contained in a DTD or a schema. When +parsing XML, UAs do not always read the DTD, and thus may not know +what the ID of an element is (though a UA may have namespace-specific +knowledge that allows it to determine which attribute is the ID +attribute for that namespace). If a style sheet designer knows or +suspects that a UA may not know what the ID of an element is, he +should use normal attribute selectors instead: +[name=p371] instead of #p371. Elements in +XML 1.0 documents without a DTD do not have IDs at all.

+ +

If an element has multiple ID attributes, all of them must be +treated as IDs for that element for the purposes of the ID +selector. Such a situation could be reached using mixtures of xml:id, +DOM3 Core, XML DTDs, and namespace-specific knowledge.

+ +

6.6. Pseudo-classes

+ +

The pseudo-class concept is introduced to permit selection based on +information that lies outside of the document tree or that cannot be +expressed using the other simple selectors.

+ +

A pseudo-class always consists of a "colon" +(:) followed by the name of the pseudo-class and +optionally by a value between parentheses.

+ +

Pseudo-classes are allowed in all sequences of simple selectors +contained in a selector. Pseudo-classes are allowed anywhere in +sequences of simple selectors, after the leading type selector or +universal selector (possibly omitted). Pseudo-class names are +case-insensitive. Some pseudo-classes are mutually exclusive, while +others can be applied simultaneously to the same +element. Pseudo-classes may be dynamic, in the sense that an element +may acquire or lose a pseudo-class while a user interacts with the +document.

+ + +

6.6.1. Dynamic pseudo-classes

+ +

Dynamic pseudo-classes classify elements on characteristics other +than their name, attributes, or content, in principle characteristics +that cannot be deduced from the document tree.

+ +

Dynamic pseudo-classes do not appear in the document source or +document tree.

+ + +
The link pseudo-classes: :link and :visited
+ +

User agents commonly display unvisited links differently from +previously visited ones. Selectors +provides the pseudo-classes :link and +:visited to distinguish them:

+ + + +

After some amount of time, user agents may choose to return a +visited link to the (unvisited) ':link' state.

+ +

The two states are mutually exclusive.

+ +
+ +

Example:

+ +

The following selector represents links carrying class + external and already visited:

+ +
a.external:visited
+ +
+ +

Note: It is possible for style sheet +authors to abuse the :link and :visited pseudo-classes to determine +which sites a user has visited without the user's consent. + +

UAs may therefore treat all links as unvisited links, or implement +other measures to preserve the user's privacy while rendering visited +and unvisited links differently.

+ +
The user action pseudo-classes +:hover, :active, and :focus
+ +

Interactive user agents sometimes change the rendering in response +to user actions. Selectors provides +three pseudo-classes for the selection of an element the user is +acting on.

+ + + +

There may be document language or implementation specific limits on +which elements can become :active or acquire +:focus.

+ +

These pseudo-classes are not mutually exclusive. An element may +match several pseudo-classes at the same time.

+ +

Selectors doesn't define if the parent of an element that is +':active' or ':hover' is also in that state.

+ +
+

Examples:

+
a:link    /* unvisited links */
+a:visited /* visited links */
+a:hover   /* user hovers */
+a:active  /* active links */
+

An example of combining dynamic pseudo-classes:

+
a:focus
+a:focus:hover
+

The last selector matches a elements that are in + the pseudo-class :focus and in the pseudo-class :hover.

+
+ +

Note: An element can be both ':visited' +and ':active' (or ':link' and ':active').

+ +

6.6.2. The target pseudo-class :target

+ +

Some URIs refer to a location within a resource. This kind of URI +ends with a "number sign" (#) followed by an anchor +identifier (called the fragment identifier).

+ +

URIs with fragment identifiers link to a certain element within the +document, known as the target element. For instance, here is a URI +pointing to an anchor named section_2 in an HTML +document:

+ +
http://example.com/html/top.html#section_2
+ +

A target element can be represented by the :target +pseudo-class. If the document's URI has no fragment identifier, then +the document has no target element.

+ +
+

Example:

+
p.note:target
+

This selector represents a p element of class + note that is the target element of the referring + URI.

+
+ +
+

CSS example:

+

Here, the :target pseudo-class is used to make the + target element red and place an image before it, if there is one:

+
*:target { color : red }
+*:target::before { content : url(target.png) }
+
+ +

6.6.3. The language pseudo-class :lang

+ +

If the document language specifies how the human language of an +element is determined, it is possible to write selectors that +represent an element based on its language. For example, in HTML [HTML4], the language is determined by a +combination of the lang attribute, the meta +element, and possibly by information from the protocol (such as HTTP +headers). XML uses an attribute called xml:lang, and +there may be other document language-specific methods for determining +the language.

+ +

The pseudo-class :lang(C) represents an element that +is in language C. Whether an element is represented by a +:lang() selector is based solely on the identifier C +being either equal to, or a hyphen-separated substring of, the +element's language value, in the same way as if performed by the '|=' operator in attribute +selectors. The identifier C does not have to be a valid language +name.

+ +

C must not be empty. (If it is, the selector is invalid.)

+ +

Note: It is recommended that +documents and protocols indicate language using codes from RFC 3066 [RFC3066] or its successor, and by means of +"xml:lang" attributes in the case of XML-based documents [XML10]. See +"FAQ: Two-letter or three-letter language codes."

+ +
+

Examples:

+

The two following selectors represent an HTML document that is in + Belgian, French, or German. The two next selectors represent + q quotations in an arbitrary element in Belgian, French, + or German.

+
html:lang(fr-be)
+html:lang(de)
+:lang(fr-be) > q
+:lang(de) > q
+
+ +

6.6.4. The UI element states pseudo-classes

+ +
The :enabled and :disabled pseudo-classes
+ +

The :enabled pseudo-class allows authors to customize +the look of user interface elements that are enabled — which the +user can select or activate in some fashion (e.g. clicking on a button +with a mouse). There is a need for such a pseudo-class because there +is no way to programmatically specify the default appearance of say, +an enabled input element without also specifying what it +would look like when it was disabled.

+ +

Similar to :enabled, :disabled allows the +author to specify precisely how a disabled or inactive user interface +element should look.

+ +

Most elements will be neither enabled nor disabled. An element is +enabled if the user can either activate it or transfer the focus to +it. An element is disabled if it could be enabled, but the user cannot +presently activate it or transfer focus to it.

+ + +
The :checked pseudo-class
+ +

Radio and checkbox elements can be toggled by the user. Some menu +items are "checked" when the user selects them. When such elements are +toggled "on" the :checked pseudo-class applies. The +:checked pseudo-class initially applies to such elements +that have the HTML4 selected and checked +attributes as described in Section +17.2.1 of HTML4, but of course the user can toggle "off" such +elements in which case the :checked pseudo-class would no +longer apply. While the :checked pseudo-class is dynamic +in nature, and is altered by user action, since it can also be based +on the presence of the semantic HTML4 selected and +checked attributes, it applies to all media. + + +

The :indeterminate pseudo-class
+ +
+ +

Radio and checkbox elements can be toggled by the user, but are +sometimes in an indeterminate state, neither checked nor unchecked. +This can be due to an element attribute, or DOM manipulation.

+ +

A future version of this specification may introduce an +:indeterminate pseudo-class that applies to such elements. +

+ +
+ + +

6.6.5. Structural pseudo-classes

+ +

Selectors introduces the concept of structural +pseudo-classes to permit selection based on extra information that lies in +the document tree but cannot be represented by other simple selectors or +combinators. + +

Note that standalone pieces of PCDATA (text nodes in the DOM) are +not counted when calculating the position of an element in the list of +children of its parent. When calculating the position of an element in +the list of children of its parent, the index numbering starts at 1. + + +

:root pseudo-class
+ +

The :root pseudo-class represents an element that is +the root of the document. In HTML 4, this is always the +HTML element. + + +

:nth-child() pseudo-class
+ +

The +:nth-child(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings +before it in the document tree, for a given positive +integer or zero value of n, and has a parent element. In +other words, this matches the bth child of an element after +all the children have been split into groups of a elements +each. For example, this allows the selectors to address every other +row in a table, and could be used to alternate the color +of paragraph text in a cycle of four. The a and +b values must be zero, negative integers or positive +integers. The index of the first child of an element is 1. + +

In addition to this, :nth-child() can take +'odd' and 'even' as arguments instead. +'odd' has the same signification as 2n+1, +and 'even' has the same signification as 2n. + + +

+

Examples:

+
tr:nth-child(2n+1) /* represents every odd row of an HTML table */
+tr:nth-child(odd)  /* same */
+tr:nth-child(2n)   /* represents every even row of an HTML table */
+tr:nth-child(even) /* same */
+
+/* Alternate paragraph colours in CSS */
+p:nth-child(4n+1) { color: navy; }
+p:nth-child(4n+2) { color: green; }
+p:nth-child(4n+3) { color: maroon; }
+p:nth-child(4n+4) { color: purple; }
+
+ +

When a=0, no repeating is used, so for example +:nth-child(0n+5) matches only the fifth child. When +a=0, the an part need not be +included, so the syntax simplifies to +:nth-child(b) and the last example simplifies +to :nth-child(5). + +

+

Examples:

+
foo:nth-child(0n+1)   /* represents an element foo, first child of its parent element */
+foo:nth-child(1)      /* same */
+
+ +

When a=1, the number may be omitted from the rule. + +

+

Examples:

+

The following selectors are therefore equivalent:

+
bar:nth-child(1n+0)   /* represents all bar elements, specificity (0,1,1) */
+bar:nth-child(n+0)    /* same */
+bar:nth-child(n)      /* same */
+bar                   /* same but lower specificity (0,0,1) */
+
+ +

If b=0, then every ath element is picked. In +such a case, the b part may be omitted. + +

+

Examples:

+
tr:nth-child(2n+0) /* represents every even row of an HTML table */
+tr:nth-child(2n) /* same */
+
+ +

If both a and b are equal to zero, the +pseudo-class represents no element in the document tree.

+ +

The value a can be negative, but only the positive +values of an+b, for +n≥0, may represent an element in the document +tree.

+ +
+

Example:

+
html|tr:nth-child(-n+6)  /* represents the 6 first rows of XHTML tables */
+
+ +

When the value b is negative, the "+" character in the +expression must be removed (it is effectively replaced by the "-" +character indicating the negative value of b).

+ +
+

Examples:

+
:nth-child(10n-1)  /* represents the 9th, 19th, 29th, etc, element */
+:nth-child(10n+9)  /* Same */
+:nth-child(10n+-1) /* Syntactically invalid, and would be ignored */
+
+ + +
:nth-last-child() pseudo-class
+ +

The :nth-last-child(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings +after it in the document tree, for a given positive +integer or zero value of n, and has a parent element. See +:nth-child() pseudo-class for the syntax of its argument. +It also accepts the 'even' and 'odd' values +as arguments. + + +

+

Examples:

+
tr:nth-last-child(-n+2)    /* represents the two last rows of an HTML table */
+
+foo:nth-last-child(odd)    /* represents all odd foo elements in their parent element,
+                              counting from the last one */
+
+ + +
:nth-of-type() pseudo-class
+ +

The :nth-of-type(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings with the same +element name before it in the document tree, for a +given zero or positive integer value of n, and has a +parent element. In other words, this matches the bth child +of that type after all the children of that type have been split into +groups of a elements each. See :nth-child() pseudo-class +for the syntax of its argument. It also accepts the +'even' and 'odd' values. + + +

+

CSS example:

+

This allows an author to alternate the position of floated images:

+
img:nth-of-type(2n+1) { float: right; }
+img:nth-of-type(2n) { float: left; }
+
+ + +
:nth-last-of-type() pseudo-class
+ +

The :nth-last-of-type(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings with the same +element name after it in the document tree, for a +given zero or positive integer value of n, and has a +parent element. See :nth-child() pseudo-class for the +syntax of its argument. It also accepts the 'even' and 'odd' values. + + +

+

Example:

+

To represent all h2 children of an XHTML + body except the first and last, one could use the + following selector:

+
body > h2:nth-of-type(n+2):nth-last-of-type(n+2)
+

In this case, one could also use :not(), although the + selector ends up being just as long:

+
body > h2:not(:first-of-type):not(:last-of-type)
+
+ + +
:first-child pseudo-class
+ +

Same as :nth-child(1). The :first-child pseudo-class +represents an element that is the first child of some other element. + + +

+

Examples:

+

The following selector represents a p element that is + the first child of a div element:

+
div > p:first-child
+

This selector can represent the p inside the + div of the following fragment:

+
<p> The last P before the note.</p>
+<div class="note">
+   <p> The first P inside the note.</p>
+</div>
but cannot represent the second p in the following +fragment: +
<p> The last P before the note.</p>
+<div class="note">
+   <h2> Note </h2>
+   <p> The first P inside the note.</p>
+</div>
+

The following two selectors are usually equivalent:

+
* > a:first-child /* a is first child of any element */
+a:first-child /* Same (assuming a is not the root element) */
+
+ +
:last-child pseudo-class
+ +

Same as :nth-last-child(1). The :last-child pseudo-class +represents an element that is the last child of some other element. + +

+

Example:

+

The following selector represents a list item li that + is the last child of an ordered list ol. +

ol > li:last-child
+
+ +
:first-of-type pseudo-class
+ +

Same as :nth-of-type(1). The :first-of-type pseudo-class +represents an element that is the first sibling of its type in the list of +children of its parent element. + +

+

Example:

+

The following selector represents a definition title +dt inside a definition list dl, this +dt being the first of its type in the list of children of +its parent element.

+
dl dt:first-of-type
+

It is a valid description for the first two dt +elements in the following example but not for the third one:

+
<dl>
+ <dt>gigogne</dt>
+ <dd>
+  <dl>
+   <dt>fusée</dt>
+   <dd>multistage rocket</dd>
+   <dt>table</dt>
+   <dd>nest of tables</dd>
+  </dl>
+ </dd>
+</dl>
+
+ +
:last-of-type pseudo-class
+ +

Same as :nth-last-of-type(1). The +:last-of-type pseudo-class represents an element that is +the last sibling of its type in the list of children of its parent +element.

+ +
+

Example:

+

The following selector represents the last data cell + td of a table row.

+
tr > td:last-of-type
+
+ +
:only-child pseudo-class
+ +

Represents an element that has a parent element and whose parent +element has no other element children. Same as +:first-child:last-child or +:nth-child(1):nth-last-child(1), but with a lower +specificity.

+ +
:only-of-type pseudo-class
+ +

Represents an element that has a parent element and whose parent +element has no other element children with the same element name. Same +as :first-of-type:last-of-type or +:nth-of-type(1):nth-last-of-type(1), but with a lower +specificity.

+ + +
:empty pseudo-class
+ +

The :empty pseudo-class represents an element that has +no children at all. In terms of the DOM, only element nodes and text +nodes (including CDATA nodes and entity references) whose data has a +non-zero length must be considered as affecting emptiness; comments, +PIs, and other nodes must not affect whether an element is considered +empty or not.

+ +
+

Examples:

+

p:empty is a valid representation of the following fragment:

+
<p></p>
+

foo:empty is not a valid representation for the + following fragments:

+
<foo>bar</foo>
+
<foo><bar>bla</bar></foo>
+
<foo>this is not <bar>:empty</bar></foo>
+
+ +

6.6.6. Blank

+ +

This section intentionally left blank.

+ + +

6.6.7. The negation pseudo-class

+ +

The negation pseudo-class, :not(X), is a +functional notation taking a simple +selector (excluding the negation pseudo-class itself and +pseudo-elements) as an argument. It represents an element that is not +represented by the argument. + + + +

+

Examples:

+

The following CSS selector matches all button + elements in an HTML document that are not disabled.

+
button:not([DISABLED])
+

The following selector represents all but FOO + elements.

+
*:not(FOO)
+

The following group of selectors represents all HTML elements + except links.

+
html|*:not(:link):not(:visited)
+
+ +

Default namespace declarations do not affect the argument of the +negation pseudo-class unless the argument is a universal selector or a +type selector.

+ +
+

Examples:

+

Assuming that the default namespace is bound to + "http://example.com/", the following selector represents all + elements that are not in that namespace:

+
*|*:not(*)
+

The following CSS selector matches any element being hovered, + regardless of its namespace. In particular, it is not limited to + only matching elements in the default namespace that are not being + hovered, and elements not in the default namespace don't match the + rule when they are being hovered.

+
*|*:not(:hover)
+
+ +

Note: the :not() pseudo allows +useless selectors to be written. For instance :not(*|*), +which represents no element at all, or foo:not(bar), +which is equivalent to foo but with a higher +specificity.

+ +

7. Pseudo-elements

+ +

Pseudo-elements create abstractions about the document tree beyond +those specified by the document language. For instance, document +languages do not offer mechanisms to access the first letter or first +line of an element's content. Pseudo-elements allow designers to refer +to this otherwise inaccessible information. Pseudo-elements may also +provide designers a way to refer to content that does not exist in the +source document (e.g., the ::before and +::after pseudo-elements give access to generated +content).

+ +

A pseudo-element is made of two colons (::) followed +by the name of the pseudo-element.

+ +

This :: notation is introduced by the current document +in order to establish a discrimination between pseudo-classes and +pseudo-elements. For compatibility with existing style sheets, user +agents must also accept the previous one-colon notation for +pseudo-elements introduced in CSS levels 1 and 2 (namely, +:first-line, :first-letter, +:before and :after). This compatibility is +not allowed for the new pseudo-elements introduced in CSS level 3.

+ +

Only one pseudo-element may appear per selector, and if present it +must appear after the sequence of simple selectors that represents the +subjects of the selector. A +future version of this specification may allow multiple +pesudo-elements per selector.

+ +

7.1. The ::first-line pseudo-element

+ +

The ::first-line pseudo-element describes the contents +of the first formatted line of an element. + +

+

CSS example:

+
p::first-line { text-transform: uppercase }
+

The above rule means "change the letters of the first line of every +paragraph to uppercase".

+
+ +

The selector p::first-line does not match any real +HTML element. It does match a pseudo-element that conforming user +agents will insert at the beginning of every paragraph.

+ +

Note that the length of the first line depends on a number of +factors, including the width of the page, the font size, etc. Thus, +an ordinary HTML paragraph such as:

+ +
+<P>This is a somewhat long HTML 
+paragraph that will be broken into several 
+lines. The first line will be identified
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

the lines of which happen to be broken as follows: + +

+THIS IS A SOMEWHAT LONG HTML PARAGRAPH THAT
+will be broken into several lines. The first
+line will be identified by a fictional tag 
+sequence. The other lines will be treated as 
+ordinary lines in the paragraph.
+
+ +

This paragraph might be "rewritten" by user agents to include the +fictional tag sequence for ::first-line. This +fictional tag sequence helps to show how properties are inherited.

+ +
+<P><P::first-line> This is a somewhat long HTML 
+paragraph that </P::first-line> will be broken into several
+lines. The first line will be identified 
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

If a pseudo-element breaks up a real element, the desired effect +can often be described by a fictional tag sequence that closes and +then re-opens the element. Thus, if we mark up the previous paragraph +with a span element:

+ +
+<P><SPAN class="test"> This is a somewhat long HTML
+paragraph that will be broken into several
+lines.</SPAN> The first line will be identified
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

the user agent could simulate start and end tags for +span when inserting the fictional tag sequence for +::first-line. + +

+<P><P::first-line><SPAN class="test"> This is a
+somewhat long HTML
+paragraph that will </SPAN></P::first-line><SPAN class="test"> be
+broken into several
+lines.</SPAN> The first line will be identified
+by a fictional tag sequence. The other lines
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

In CSS, the ::first-line pseudo-element can only be +attached to a block-level element, an inline-block, a table-caption, +or a table-cell.

+ +

The "first formatted line" of an +element may occur inside a +block-level descendant in the same flow (i.e., a block-level +descendant that is not positioned and not a float). E.g., the first +line of the div in <DIV><P>This +line...</P></DIV> is the first line of the p (assuming +that both p and div are block-level). + +

The first line of a table-cell or inline-block cannot be the first +formatted line of an ancestor element. Thus, in <DIV><P +STYLE="display: inline-block">Hello<BR>Goodbye</P> +etcetera</DIV> the first formatted line of the +div is not the line "Hello". + +

Note that the first line of the p in this +fragment: <p><br>First... doesn't contain any +letters (assuming the default style for br in HTML +4). The word "First" is not on the first formatted line. + +

A UA should act as if the fictional start tags of the +::first-line pseudo-elements were nested just inside the +innermost enclosing block-level element. (Since CSS1 and CSS2 were +silent on this case, authors should not rely on this behavior.) Here +is an example. The fictional tag sequence for

+ +
+<DIV>
+  <P>First paragraph</P>
+  <P>Second paragraph</P>
+</DIV>
+
+ +

is

+ +
+<DIV>
+  <P><DIV::first-line><P::first-line>First paragraph</P::first-line></DIV::first-line></P>
+  <P><P::first-line>Second paragraph</P::first-line></P>
+</DIV>
+
+ +

The ::first-line pseudo-element is similar to an +inline-level element, but with certain restrictions. In CSS, the +following properties apply to a ::first-line +pseudo-element: font properties, color property, background +properties, 'word-spacing', 'letter-spacing', 'text-decoration', +'vertical-align', 'text-transform', 'line-height'. UAs may apply other +properties as well.

+ + +

7.2. The ::first-letter pseudo-element

+ +

The ::first-letter pseudo-element represents the first +letter of the first line of a block, if it is not preceded by any +other content (such as images or inline tables) on its line. The +::first-letter pseudo-element may be used for "initial caps" and "drop +caps", which are common typographical effects. This type of initial +letter is similar to an inline-level element if its 'float' property +is 'none'; otherwise, it is similar to a floated element.

+ +

In CSS, these are the properties that apply to ::first-letter +pseudo-elements: font properties, 'text-decoration', 'text-transform', +'letter-spacing', 'word-spacing' (when appropriate), 'line-height', +'float', 'vertical-align' (only if 'float' is 'none'), margin +properties, padding properties, border properties, color property, +background properties. UAs may apply other properties as well. To +allow UAs to render a typographically correct drop cap or initial cap, +the UA may choose a line-height, width and height based on the shape +of the letter, unlike for normal elements.

+ +
+

Example:

+

This example shows a possible rendering of an initial cap. Note +that the 'line-height' that is inherited by the ::first-letter +pseudo-element is 1.1, but the UA in this example has computed the +height of the first letter differently, so that it doesn't cause any +unnecessary space between the first two lines. Also note that the +fictional start tag of the first letter is inside the span, and thus +the font weight of the first letter is normal, not bold as the span: +

+p { line-height: 1.1 }
+p::first-letter { font-size: 3em; font-weight: normal }
+span { font-weight: bold }
+...
+<p><span>Het hemelsche</span> gerecht heeft zich ten lange lesten<br>
+Erbarremt over my en mijn benaeuwde vesten<br>
+En arme burgery, en op mijn volcx gebed<br>
+En dagelix geschrey de bange stad ontzet.
+
+
+

Image illustrating the ::first-letter pseudo-element +

+
+ +
+

The following CSS will make a drop cap initial letter span about two lines:

+ +
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<HTML>
+ <HEAD>
+  <TITLE>Drop cap initial letter</TITLE>
+  <STYLE type="text/css">
+   P               { font-size: 12pt; line-height: 1.2 }
+   P::first-letter { font-size: 200%; font-weight: bold; float: left }
+   SPAN            { text-transform: uppercase }
+  </STYLE>
+ </HEAD>
+ <BODY>
+  <P><SPAN>The first</SPAN> few words of an article
+    in The Economist.</P>
+ </BODY>
+</HTML>
+
+ +

This example might be formatted as follows:

+ +
+

Image illustrating the combined effect of the ::first-letter and ::first-line pseudo-elements

+
+ +

The fictional tag sequence is:

+ +
+<P>
+<SPAN>
+<P::first-letter>
+T
+</P::first-letter>he first
+</SPAN> 
+few words of an article in the Economist.
+</P>
+
+ +

Note that the ::first-letter pseudo-element tags abut +the content (i.e., the initial character), while the ::first-line +pseudo-element start tag is inserted right after the start tag of the +block element.

+ +

In order to achieve traditional drop caps formatting, user agents +may approximate font sizes, for example to align baselines. Also, the +glyph outline may be taken into account when formatting.

+ +

Punctuation (i.e, characters defined in Unicode in the "open" (Ps), +"close" (Pe), "initial" (Pi). "final" (Pf) and "other" (Po) +punctuation classes), that precedes or follows the first letter should +be included. [UNICODE]

+ +
+

Quotes that precede the
+first letter should be included.

+
+ +

The ::first-letter also applies if the first letter is +in fact a digit, e.g., the "6" in "67 million dollars is a lot of +money."

+ +

In CSS, the ::first-letter pseudo-element applies to +block, list-item, table-cell, table-caption, and inline-block +elements. A future version of this specification +may allow this pesudo-element to apply to more element +types.

+ +

The ::first-letter pseudo-element can be used with all +such elements that contain text, or that have a descendant in the same +flow that contains text. A UA should act as if the fictional start tag +of the ::first-letter pseudo-element is just before the first text of +the element, even if that first text is in a descendant.

+ +
+

Example:

+

The fictional tag sequence for this HTMLfragment: +

<div>
+<p>The first text.
+

is: +

<div>
+<p><div::first-letter><p::first-letter>T</...></...>he first text.
+
+ +

The first letter of a table-cell or inline-block cannot be the +first letter of an ancestor element. Thus, in <DIV><P +STYLE="display: inline-block">Hello<BR>Goodbye</P> +etcetera</DIV> the first letter of the div is not the +letter "H". In fact, the div doesn't have a first letter. + +

The first letter must occur on the first formatted line. For example, in +this fragment: <p><br>First... the first line +doesn't contain any letters and ::first-letter doesn't +match anything (assuming the default style for br in HTML +4). In particular, it does not match the "F" of "First." + +

In CSS, if an element is a list item ('display: list-item'), the +::first-letter applies to the first letter in the +principal box after the marker. UAs may ignore +::first-letter on list items with 'list-style-position: +inside'. If an element has ::before or +::after content, the ::first-letter applies +to the first letter of the element including that content. + +

+

Example:

+

After the rule 'p::before {content: "Note: "}', the selector +'p::first-letter' matches the "N" of "Note".

+
+ +

Some languages may have specific rules about how to treat certain +letter combinations. In Dutch, for example, if the letter combination +"ij" appears at the beginning of a word, both letters should be +considered within the ::first-letter pseudo-element. + +

If the letters that would form the ::first-letter are not in the +same element, such as "'T" in <p>'<em>T..., the UA +may create a ::first-letter pseudo-element from one of the elements, +both elements, or simply not create a pseudo-element.

+ +

Similarly, if the first letter(s) of the block are not at the start +of the line (for example due to bidirectional reordering), then the UA +need not create the pseudo-element(s). + +

+

Example:

+

The following example illustrates +how overlapping pseudo-elements may interact. The first letter of +each P element will be green with a font size of '24pt'. The rest of +the first formatted line will be 'blue' while the rest of the +paragraph will be 'red'.

+ +
p { color: red; font-size: 12pt }
+p::first-letter { color: green; font-size: 200% }
+p::first-line { color: blue }
+
+<P>Some text that ends up on two lines</P>
+ +

Assuming that a line break will occur before the word "ends", the +fictional tag +sequence for this fragment might be:

+ +
<P>
+<P::first-line>
+<P::first-letter> 
+S 
+</P::first-letter>ome text that 
+</P::first-line> 
+ends up on two lines 
+</P>
+ +

Note that the ::first-letter element is inside the ::first-line +element. Properties set on ::first-line are inherited by +::first-letter, but are overridden if the same property is set on +::first-letter.

+
+ + +

7.3. The ::selection pseudo-element

+ +

The ::selection pseudo-element applies to the portion +of a document that has been highlighted by the user. This also +applies, for example, to selected text within an editable text +field. This pseudo-element should not be confused with the :checked pseudo-class (which used to be +named :selected) + +

Although the ::selection pseudo-element is dynamic in +nature, and is altered by user action, it is reasonable to expect that +when a UA re-renders to a static medium (such as a printed page, see +[CSS21]) which was originally rendered to a +dynamic medium (like screen), the UA may wish to transfer the current +::selection state to that other medium, and have all the +appropriate formatting and rendering take effect as well. This is not +required — UAs may omit the ::selection +pseudo-element for static media. + +

These are the CSS properties that apply to ::selection +pseudo-elements: color, background, cursor (optional), outline +(optional). The computed value of the 'background-image' property on +::selection may be ignored. + + +

7.4. The ::before and ::after pseudo-elements

+ +

The ::before and ::after pseudo-elements +can be used to describe generated content before or after an element's +content. They are explained in CSS 2.1 [CSS21].

+ +

When the ::first-letter and ::first-line +pseudo-elements are combined with ::before and +::after, they apply to the first letter or line of the +element including the inserted text.

+ +

8. Combinators

+ +

8.1. Descendant combinator

+ +

At times, authors may want selectors to describe an element that is +the descendant of another element in the document tree (e.g., "an +EM element that is contained within an H1 +element"). Descendant combinators express such a relationship. A +descendant combinator is white space that +separates two sequences of simple selectors. A selector of the form +"A B" represents an element B that is an +arbitrary descendant of some ancestor element A. + +

+

Examples:

+

For example, consider the following selector:

+
h1 em
+

It represents an em element being the descendant of + an h1 element. It is a correct and valid, but partial, + description of the following fragment:

+
<h1>This <span class="myclass">headline
+is <em>very</em> important</span></h1>
+

The following selector:

+
div * p
+

represents a p element that is a grandchild or later + descendant of a div element. Note the whitespace on + either side of the "*" is not part of the universal selector; the + whitespace is a combinator indicating that the DIV must be the + ancestor of some element, and that that element must be an ancestor + of the P.

+

The following selector, which combines descendant combinators and + attribute selectors, represents an + element that (1) has the href attribute set and (2) is + inside a p that is itself inside a div:

+
div p *[href]
+
+ +

8.2. Child combinators

+ +

A child combinator describes a childhood relationship +between two elements. A child combinator is made of the +"greater-than sign" (>) character and +separates two sequences of simple selectors. + + +

+

Examples:

+

The following selector represents a p element that is + child of body:

+
body > p
+

The following example combines descendant combinators and child + combinators.

+
div ol>li p
+

It represents a p element that is a descendant of an + li element; the li element must be the + child of an ol element; the ol element must + be a descendant of a div. Notice that the optional white + space around the ">" combinator has been left out.

+
+ +

For information on selecting the first child of an element, please +see the section on the :first-child pseudo-class +above.

+ +

8.3. Sibling combinators

+ +

There are two different sibling combinators: the adjacent sibling +combinator and the general sibling combinator. In both cases, +non-element nodes (e.g. text between elements) are ignored when +considering adjacency of elements.

+ +

8.3.1. Adjacent sibling combinator

+ +

The adjacent sibling combinator is made of the "plus +sign" (U+002B, +) character that separates two +sequences of simple selectors. The elements represented by the two +sequences share the same parent in the document tree and the element +represented by the first sequence immediately precedes the element +represented by the second one.

+ +
+

Examples:

+

The following selector represents a p element + immediately following a math element:

+
math + p
+

The following selector is conceptually similar to the one in the + previous example, except that it adds an attribute selector — it + adds a constraint to the h1 element, that it must have + class="opener":

+
h1.opener + h2
+
+ + +

8.3.2. General sibling combinator

+ +

The general sibling combinator is made of the "tilde" +(U+007E, ~) character that separates two sequences of +simple selectors. The elements represented by the two sequences share +the same parent in the document tree and the element represented by +the first sequence precedes (not necessarily immediately) the element +represented by the second one.

+ +
+

Example:

+
h1 ~ pre
+

represents a pre element following an h1. It + is a correct and valid, but partial, description of:

+
<h1>Definition of the function a</h1>
+<p>Function a(x) has to be applied to all figures in the table.</p>
+<pre>function a(x) = 12x/13.5</pre>
+
+ +

9. Calculating a selector's specificity

+ +

A selector's specificity is calculated as follows:

+ + + +

Selectors inside the negation pseudo-class +are counted like any other, but the negation itself does not count as +a pseudo-class.

+ +

Concatenating the three numbers a-b-c (in a number system with a +large base) gives the specificity.

+ +
+

Examples:

+
*               /* a=0 b=0 c=0 -> specificity =   0 */
+LI              /* a=0 b=0 c=1 -> specificity =   1 */
+UL LI           /* a=0 b=0 c=2 -> specificity =   2 */
+UL OL+LI        /* a=0 b=0 c=3 -> specificity =   3 */
+H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity =  11 */
+UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */
+LI.red.level    /* a=0 b=2 c=1 -> specificity =  21 */
+#x34y           /* a=1 b=0 c=0 -> specificity = 100 */
+#s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 101 */
+
+
+ +

Note: the specificity of the styles +specified in an HTML style attribute is described in CSS +2.1. [CSS21].

+ +

10. The grammar of Selectors

+ +

10.1. Grammar

+ +

The grammar below defines the syntax of Selectors. It is globally +LL(1) and can be locally LL(2) (but note that most UA's should not use +it directly, since it doesn't express the parsing conventions). The +format of the productions is optimized for human consumption and some +shorthand notations beyond Yacc (see [YACC]) +are used:

+ + + +

The productions are:

+ +
selectors_group
+  : selector [ COMMA S* selector ]*
+  ;
+
+selector
+  : simple_selector_sequence [ combinator simple_selector_sequence ]*
+  ;
+
+combinator
+  /* combinators can be surrounded by white space */
+  : PLUS S* | GREATER S* | TILDE S* | S+
+  ;
+
+simple_selector_sequence
+  : [ type_selector | universal ]
+    [ HASH | class | attrib | pseudo | negation ]*
+  | [ HASH | class | attrib | pseudo | negation ]+
+  ;
+
+type_selector
+  : [ namespace_prefix ]? element_name
+  ;
+
+namespace_prefix
+  : [ IDENT | '*' ]? '|'
+  ;
+
+element_name
+  : IDENT
+  ;
+
+universal
+  : [ namespace_prefix ]? '*'
+  ;
+
+class
+  : '.' IDENT
+  ;
+
+attrib
+  : '[' S* [ namespace_prefix ]? IDENT S*
+        [ [ PREFIXMATCH |
+            SUFFIXMATCH |
+            SUBSTRINGMATCH |
+            '=' |
+            INCLUDES |
+            DASHMATCH ] S* [ IDENT | STRING ] S*
+        ]? ']'
+  ;
+
+pseudo
+  /* '::' starts a pseudo-element, ':' a pseudo-class */
+  /* Exceptions: :first-line, :first-letter, :before and :after. */
+  /* Note that pseudo-elements are restricted to one per selector and */
+  /* occur only in the last simple_selector_sequence. */
+  : ':' ':'? [ IDENT | functional_pseudo ]
+  ;
+
+functional_pseudo
+  : FUNCTION S* expression ')'
+  ;
+
+expression
+  /* In CSS3, the expressions are identifiers, strings, */
+  /* or of the form "an+b" */
+  : [ [ PLUS | '-' | DIMENSION | NUMBER | STRING | IDENT ] S* ]+
+  ;
+
+negation
+  : NOT S* negation_arg S* ')'
+  ;
+
+negation_arg
+  : type_selector | universal | HASH | class | attrib | pseudo
+  ;
+ + +

10.2. Lexical scanner

+ +

The following is the tokenizer, written in Flex (see +[FLEX]) notation. The tokenizer is +case-insensitive.

+ +

The two occurrences of "\377" represent the highest character +number that current versions of Flex can deal with (decimal 255). They +should be read as "\4177777" (decimal 1114111), which is the highest +possible code point in Unicode/ISO-10646. [UNICODE]

+ +
%option case-insensitive
+
+ident     [-]?{nmstart}{nmchar}*
+name      {nmchar}+
+nmstart   [_a-z]|{nonascii}|{escape}
+nonascii  [^\0-\177]
+unicode   \\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?
+escape    {unicode}|\\[^\n\r\f0-9a-f]
+nmchar    [_a-z0-9-]|{nonascii}|{escape}
+num       [0-9]+|[0-9]*\.[0-9]+
+string    {string1}|{string2}
+string1   \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*\"
+string2   \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*\'
+invalid   {invalid1}|{invalid2}
+invalid1  \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*
+invalid2  \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*
+nl        \n|\r\n|\r|\f
+w         [ \t\r\n\f]*
+
+%%
+
+[ \t\r\n\f]+     return S;
+
+"~="             return INCLUDES;
+"|="             return DASHMATCH;
+"^="             return PREFIXMATCH;
+"$="             return SUFFIXMATCH;
+"*="             return SUBSTRINGMATCH;
+{ident}          return IDENT;
+{string}         return STRING;
+{ident}"("       return FUNCTION;
+{num}            return NUMBER;
+"#"{name}        return HASH;
+{w}"+"           return PLUS;
+{w}">"           return GREATER;
+{w}","           return COMMA;
+{w}"~"           return TILDE;
+":not("          return NOT;
+@{ident}         return ATKEYWORD;
+{invalid}        return INVALID;
+{num}%           return PERCENTAGE;
+{num}{ident}     return DIMENSION;
+"<!--"           return CDO;
+"-->"            return CDC;
+
+"url("{w}{string}{w}")"                           return URI;
+"url("{w}([!#$%&*-~]|{nonascii}|{escape})*{w}")"  return URI;
+U\+[0-9a-f?]{1,6}(-[0-9a-f]{1,6})?                return UNICODE_RANGE;
+
+\/\*[^*]*\*+([^/*][^*]*\*+)*\/                    /* ignore comments */
+
+.                return *yytext;
+ + + +

11. Namespaces and down-level clients

+ +

An important issue is the interaction of CSS selectors with XML +documents in web clients that were produced prior to this +document. Unfortunately, due to the fact that namespaces must be +matched based on the URI which identifies the namespace, not the +namespace prefix, some mechanism is required to identify namespaces in +CSS by their URI as well. Without such a mechanism, it is impossible +to construct a CSS style sheet which will properly match selectors in +all cases against a random set of XML documents. However, given +complete knowledge of the XML document to which a style sheet is to be +applied, and a limited use of namespaces within the XML document, it +is possible to construct a style sheet in which selectors would match +elements and attributes correctly.

+ +

It should be noted that a down-level CSS client will (if it +properly conforms to CSS forward compatible parsing rules) ignore all +@namespace at-rules, as well as all style rules that make +use of namespace qualified element type or attribute selectors. The +syntax of delimiting namespace prefixes in CSS was deliberately chosen +so that down-level CSS clients would ignore the style rules rather +than possibly match them incorrectly.

+ +

The use of default namespaces in CSS makes it possible to write +element type selectors that will function in both namespace aware CSS +clients as well as down-level clients. It should be noted that +down-level clients may incorrectly match selectors against XML +elements in other namespaces.

+ +

The following are scenarios and examples in which it is possible to +construct style sheets which would function properly in web clients +that do not implement this proposal.

+ +
    +
  1. + +

    The XML document does not use namespaces.

    + +
      + +
    • In this case, it is obviously not necessary to declare or use + namespaces in the style sheet. Standard CSS element type and + attribute selectors will function adequately in a down-level + client.
    • + +
    • In a CSS namespace aware client, the default behavior of + element selectors matching without regard to namespace will + function properly against all elements, since no namespaces are + present. However, the use of specific element type selectors that + match only elements that have no namespace ("|name") + will guarantee that selectors will match only XML elements that do + not have a declared namespace.
    • + +
    + +
  2. + +
  3. + +

    The XML document defines a single, default namespace used + throughout the document. No namespace prefixes are used in element + names.

    + +
      + +
    • In this case, a down-level client will function as if + namespaces were not used in the XML document at all. Standard CSS + element type and attribute selectors will match against all + elements.
    • + +
    + +
  4. + +
  5. + +

    The XML document does not use a default namespace, all + namespace prefixes used are known to the style sheet author, and + there is a direct mapping between namespace prefixes and namespace + URIs. (A given prefix may only be mapped to one namespace URI + throughout the XML document; there may be multiple prefixes mapped + to the same URI).

    + +
      + +
    • In this case, the down-level client will view and match + element type and attribute selectors based on their fully + qualified name, not the local part as outlined in the Type selectors and Namespaces section. CSS + selectors may be declared using an escaped colon "\:" + to describe the fully qualified names, e.g. + "html\:h1" will match + <html:h1>. Selectors using the qualified name + will only match XML elements that use the same prefix. Other + namespace prefixes used in the XML that are mapped to the same URI + will not match as expected unless additional CSS style rules are + declared for them.
    • + +
    • Note that selectors declared in this fashion will + only match in down-level clients. A CSS namespace aware + client will match element type and attribute selectors based on + the name's local part. Selectors declared with the fully + qualified name will not match (unless there is no namespace prefix + in the fully qualified name).
    • + +
    + +
  6. + +
+ +

In other scenarios: when the namespace prefixes used in the XML are +not known in advance by the style sheet author; or a combination of +elements with no namespace are used in conjunction with elements using +a default namespace; or the same namespace prefix is mapped to +different namespace URIs within the same document, or in +different documents; it is impossible to construct a CSS style sheet +that will function properly against all elements in those documents, +unless, the style sheet is written using a namespace URI syntax (as +outlined in this document or similar) and the document is processed by +a CSS and XML namespace aware client.

+ +

12. Profiles

+ +

Each specification using Selectors must define the subset of W3C +Selectors it allows and excludes, and describe the local meaning of +all the components of that subset.

+ +

Non normative examples: + +

+ + + + + + + + + + + + + + + +
Selectors profile
SpecificationCSS level 1
Acceptstype selectors
class selectors
ID selectors
:link, + :visited and :active pseudo-classes
descendant combinator +
::first-line and ::first-letter pseudo-elements
Excludes + +

universal selector
attribute selectors
:hover and :focus + pseudo-classes
:target pseudo-class
:lang() pseudo-class
all UI + element states pseudo-classes
all structural + pseudo-classes
negation pseudo-class
all + UI element fragments pseudo-elements
::before and ::after + pseudo-elements
child combinators
sibling combinators + +

namespaces

Extra constraintsonly one class selector allowed per sequence of simple + selectors


+ + + + + + + + + + + + + + + +
Selectors profile
SpecificationCSS level 2
Acceptstype selectors
universal selector
attribute presence and + values selectors
class selectors
ID selectors
:link, :visited, + :active, :hover, :focus, :lang() and :first-child pseudo-classes +
descendant combinator
child combinator
adjacent sibling + combinator
::first-line and ::first-letter pseudo-elements
::before + and ::after pseudo-elements
Excludes + +

content selectors
substring matching attribute + selectors
:target pseudo-classes
all UI element + states pseudo-classes
all structural pseudo-classes other + than :first-child
negation pseudo-class
all UI element + fragments pseudo-elements
general sibling combinators + +

namespaces

Extra constraintsmore than one class selector per sequence of simple selectors (CSS1 + constraint) allowed
+ +

In CSS, selectors express pattern matching rules that determine which style +rules apply to elements in the document tree. + +

The following selector (CSS level 2) will match all anchors a +with attribute name set inside a section 1 header h1: +

h1 a[name]
+ +

All CSS declarations attached to such a selector are applied to elements +matching it.

+ +
+ + + + + + + + + + + + + + + + +
Selectors profile
SpecificationSTTS 3
Accepts + +

type selectors
universal selectors
attribute selectors
class + selectors
ID selectors
all structural pseudo-classes
+ all combinators + +

namespaces

Excludesnon-accepted pseudo-classes
pseudo-elements
Extra constraintssome selectors and combinators are not allowed in fragment + descriptions on the right side of STTS declarations.
+ +

Selectors can be used in STTS 3 in two different + manners: +

    +
  1. a selection mechanism equivalent to CSS selection mechanism: declarations + attached to a given selector are applied to elements matching that selector, +
  2. fragment descriptions that appear on the right side of declarations. +
+ +

13. Conformance and requirements

+ +

This section defines conformance with the present specification only. + +

The inability of a user agent to implement part of this specification due to +the limitations of a particular device (e.g., non interactive user agents will +probably not implement dynamic pseudo-classes because they make no sense without +interactivity) does not imply non-conformance. + +

All specifications reusing Selectors must contain a Profile listing the +subset of Selectors it accepts or excludes, and describing the constraints +it adds to the current specification. + +

Invalidity is caused by a parsing error, e.g. an unrecognized token or a token +which is not allowed at the current parsing point. + +

User agents must observe the rules for handling parsing errors: +

+ +

Specifications reusing Selectors must define how to handle parsing +errors. (In the case of CSS, the entire rule in which the selector is +used is dropped.)

+ + + +

14. Tests

+ +

This specification has a test +suite allowing user agents to verify their basic conformance to +the specification. This test suite does not pretend to be exhaustive +and does not cover all possible combined cases of Selectors.

+ +

15. Acknowledgements

+ +

The CSS working group would like to thank everyone who has sent +comments on this specification over the years.

+ +

The working group would like to extend special thanks to Donna +McManus, Justin Baker, Joel Sklar, and Molly Ives Brower who perfermed +the final editorial review.

+ +

16. References

+ +
+ +
[CSS1] +
Bert Bos, Håkon Wium Lie; "Cascading Style Sheets, level 1", W3C Recommendation, 17 Dec 1996, revised 11 Jan 1999 +
(http://www.w3.org/TR/REC-CSS1) + +
[CSS21] +
Bert Bos, Tantek Çelik, Ian Hickson, Håkon Wium Lie, editors; "Cascading Style Sheets, level 2 revision 1", W3C Working Draft, 13 June 2005 +
(http://www.w3.org/TR/CSS21) + +
[CWWW] +
Martin J. Dürst, François Yergeau, Misha Wolf, Asmus Freytag, Tex Texin, editors; "Character Model for the World Wide Web", W3C Recommendation, 15 February 2005 +
(http://www.w3.org/TR/charmod/) + +
[FLEX] +
"Flex: The Lexical Scanner Generator", Version 2.3.7, ISBN 1882114213 + +
[HTML4] +
Dave Ragget, Arnaud Le Hors, Ian Jacobs, editors; "HTML 4.01 Specification", W3C Recommendation, 24 December 1999 +
(http://www.w3.org/TR/html4/) + +
[MATH] +
Patrick Ion, Robert Miner, editors; "Mathematical Markup Language (MathML) 1.01", W3C Recommendation, revision of 7 July 1999 +
(http://www.w3.org/TR/REC-MathML/) + +
[RFC3066] +
H. Alvestrand; "Tags for the Identification of Languages", Request for Comments 3066, January 2001 +
(http://www.ietf.org/rfc/rfc3066.txt) + +
[STTS] +
Daniel Glazman; "Simple Tree Transformation Sheets 3", Electricité de France, submission to the W3C, 11 November 1998 +
(http://www.w3.org/TR/NOTE-STTS3) + +
[SVG] +
Jon Ferraiolo, 藤沢 淳, Dean Jackson, editors; "Scalable Vector Graphics (SVG) 1.1 Specification", W3C Recommendation, 14 January 2003 +
(http://www.w3.org/TR/SVG/) + +
[UNICODE]
+
The Unicode Standard, Version 4.1, The Unicode Consortium. Boston, MA, Addison-Wesley, March 2005. ISBN 0-321-18578-1, as amended by Unicode 4.0.1 and Unicode 4.1.0. +
(http://www.unicode.org/versions/)
+ +
[XML10] +
Tim Bray, Jean Paoli, C. M. Sperberg-McQueen, Eve Maler, François Yergeau, editors; "Extensible Markup Language (XML) 1.0 (Third Edition)", W3C Recommendation, 4 February 2004 +
(http://www.w3.org/TR/REC-xml/) + +
[XMLNAMES] +
Tim Bray, Dave Hollander, Andrew Layman, editors; "Namespaces in XML", W3C Recommendation, 14 January 1999 +
(http://www.w3.org/TR/REC-xml-names/) + +
[YACC] +
S. C. Johnson; "YACC — Yet another compiler compiler", Technical Report, Murray Hill, 1975 + +
+ +
+ test +
+
+
+ test +
+ test +
+
+
+ test +
+
+
+
+ +
+ d1d1 + d2d2 + d3d3 + d4d4 + d5d5 + d6d6 + + + + + + +
+
+ d1 + d1 + + d2 + d2 + + d3 + d3 + + d4 + d4 + + d5 + d5 + + d6 + d6 + +
+ + + diff --git a/test_new/browser/fixtures/slick/template-quirks.html b/test_new/browser/fixtures/slick/template-quirks.html new file mode 100644 index 0000000..fb8aef0 --- /dev/null +++ b/test_new/browser/fixtures/slick/template-quirks.html @@ -0,0 +1,2932 @@ + + + + + + + + + template html with no doctype + + + +
+

W3C + +

Selectors

+ +

W3C Working Draft 15 December 2005

+ +
+ +
This version: + +
+ http://www.w3.org/TR/2005/WD-css3-selectors-20051215 + +
Latest version: + +
+ http://www.w3.org/TR/css3-selectors + +
Previous version: + +
+ http://www.w3.org/TR/2001/CR-css3-selectors-20011113 + +
Editors: + +
Daniel Glazman (Invited Expert)
+ +
Tantek Çelik (Invited Expert) + +
Ian Hickson (Google) + +
Peter Linss (former editor, Netscape/AOL) + +
John Williams (former editor, Quark, Inc.) + +
+ +
+ +
+ +

Abstract

+ +

Selectors are patterns that match against elements in a + tree. Selectors have been optimized for use with HTML and XML, and + are designed to be usable in performance-critical code.

+ +

CSS (Cascading + Style Sheets) is a language for describing the rendering of HTML and XML documents on + screen, on paper, in speech, etc. CSS uses Selectors for binding + style properties to elements in the document. This document + describes extensions to the selectors defined in CSS level 2. These + extended selectors will be used by CSS level 3. + +

Selectors define the following function:

+ +
expression ∗ element → boolean
+ +

That is, given an element and a selector, this specification + defines whether that element matches the selector.

+ +

These expressions can also be used, for instance, to select a set + of elements, or a single element from a set of elements, by + evaluating the expression across all the elements in a + subtree. STTS (Simple Tree Transformation Sheets), a + language for transforming XML trees, uses this mechanism. [STTS]

+ +

Status of this document

+ +

This section describes the status of this document at the + time of its publication. Other documents may supersede this + document. A list of current W3C publications and the latest revision + of this technical report can be found in the W3C technical reports index at + http://www.w3.org/TR/.

+ +

This document describes the selectors that already exist in CSS1 and CSS2, and + also proposes new selectors for CSS3 and other languages that may need them.

+ +

The CSS Working Group doesn't expect that all implementations of + CSS3 will have to implement all selectors. Instead, there will + probably be a small number of variants of CSS3, called profiles. For + example, it may be that only a profile for interactive user agents + will include all of the selectors.

+ +

This specification is a last call working draft for the the CSS Working Group + (Style Activity). This + document is a revision of the Candidate + Recommendation dated 2001 November 13, and has incorporated + implementation feedback received in the past few years. It is + expected that this last call will proceed straight to Proposed + Recommendation stage since it is believed that interoperability will + be demonstrable.

+ +

All persons are encouraged to review and implement this + specification and return comments to the (archived) + public mailing list www-style + (see instructions). W3C + Members can also send comments directly to the CSS Working + Group. + The deadline for comments is 14 January 2006.

+ +

This is still a draft document and may be updated, replaced, or + obsoleted by other documents at any time. It is inappropriate to + cite a W3C Working Draft as other than "work in progress". + +

This document may be available in translation. + The English version of this specification is the only normative + version. + +

+ +

Table of contents

+ + + +
+ +

1. Introduction

+ +

1.1. Dependencies

+ +

Some features of this specification are specific to CSS, or have + particular limitations or rules specific to CSS. In this + specification, these have been described in terms of CSS2.1. [CSS21]

+ +

1.2. Terminology

+ +

All of the text of this specification is normative except + examples, notes, and sections explicitly marked as + non-normative.

+ +

1.3. Changes from CSS2

+ +

This section is non-normative.

+ +

The main differences between the selectors in CSS2 and those in + Selectors are: + +

+ +

2. Selectors

+ +

This section is non-normative, as it merely summarizes the +following sections.

+ +

A Selector represents a structure. This structure can be used as a +condition (e.g. in a CSS rule) that determines which elements a +selector matches in the document tree, or as a flat description of the +HTML or XML fragment corresponding to that structure.

+ +

Selectors may range from simple element names to rich contextual +representations.

+ +

The following table summarizes the Selector syntax:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PatternMeaningDescribed in sectionFirst defined in CSS level
*any elementUniversal + selector2
Ean element of type EType selector1
E[foo]an E element with a "foo" attributeAttribute + selectors2
E[foo="bar"]an E element whose "foo" attribute value is exactly + equal to "bar"Attribute + selectors2
E[foo~="bar"]an E element whose "foo" attribute value is a list of + space-separated values, one of which is exactly equal to "bar"Attribute + selectors2
E[foo^="bar"]an E element whose "foo" attribute value begins exactly + with the string "bar"Attribute + selectors3
E[foo$="bar"]an E element whose "foo" attribute value ends exactly + with the string "bar"Attribute + selectors3
E[foo*="bar"]an E element whose "foo" attribute value contains the + substring "bar"Attribute + selectors3
E[hreflang|="en"]an E element whose "hreflang" attribute has a hyphen-separated + list of values beginning (from the left) with "en"Attribute + selectors2
E:rootan E element, root of the documentStructural + pseudo-classes3
E:nth-child(n)an E element, the n-th child of its parentStructural + pseudo-classes3
E:nth-last-child(n)an E element, the n-th child of its parent, counting + from the last oneStructural + pseudo-classes3
E:nth-of-type(n)an E element, the n-th sibling of its typeStructural + pseudo-classes3
E:nth-last-of-type(n)an E element, the n-th sibling of its type, counting + from the last oneStructural + pseudo-classes3
E:first-childan E element, first child of its parentStructural + pseudo-classes2
E:last-childan E element, last child of its parentStructural + pseudo-classes3
E:first-of-typean E element, first sibling of its typeStructural + pseudo-classes3
E:last-of-typean E element, last sibling of its typeStructural + pseudo-classes3
E:only-childan E element, only child of its parentStructural + pseudo-classes3
E:only-of-typean E element, only sibling of its typeStructural + pseudo-classes3
E:emptyan E element that has no children (including text + nodes)Structural + pseudo-classes3
E:link
E:visited
an E element being the source anchor of a hyperlink of + which the target is not yet visited (:link) or already visited + (:visited)The link + pseudo-classes1
E:active
E:hover
E:focus
an E element during certain user actionsThe user + action pseudo-classes1 and 2
E:targetan E element being the target of the referring URIThe target + pseudo-class3
E:lang(fr)an element of type E in language "fr" (the document + language specifies how language is determined)The :lang() + pseudo-class2
E:enabled
E:disabled
a user interface element E which is enabled or + disabledThe UI element states + pseudo-classes3
E:checkeda user interface element E which is checked (for instance a radio-button or checkbox)The UI element states + pseudo-classes3
E::first-linethe first formatted line of an E elementThe ::first-line + pseudo-element1
E::first-letterthe first formatted letter of an E elementThe ::first-letter + pseudo-element1
E::selectionthe portion of an E element that is currently + selected/highlighted by the userThe UI element + fragments pseudo-elements3
E::beforegenerated content before an E elementThe ::before + pseudo-element2
E::aftergenerated content after an E elementThe ::after + pseudo-element2
E.warningan E element whose class is +"warning" (the document language specifies how class is determined).Class + selectors1
E#myidan E element with ID equal to "myid".ID + selectors1
E:not(s)an E element that does not match simple selector sNegation + pseudo-class3
E Fan F element descendant of an E elementDescendant + combinator1
E > Fan F element child of an E elementChild + combinator2
E + Fan F element immediately preceded by an E elementAdjacent sibling combinator2
E ~ Fan F element preceded by an E elementGeneral sibling combinator3
+ +

The meaning of each selector is derived from the table above by +prepending "matches" to the contents of each cell in the "Meaning" +column.

+ +

3. Case sensitivity

+ +

The case sensitivity of document language element names, attribute +names, and attribute values in selectors depends on the document +language. For example, in HTML, element names are case-insensitive, +but in XML, they are case-sensitive.

+ +

4. Selector syntax

+ +

A selector is a chain of one +or more sequences of simple selectors +separated by combinators.

+ +

A sequence of simple selectors +is a chain of simple selectors +that are not separated by a combinator. It +always begins with a type selector or a +universal selector. No other type +selector or universal selector is allowed in the sequence.

+ +

A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, content selector, or pseudo-class. One pseudo-element may be appended to the last +sequence of simple selectors.

+ +

Combinators are: white space, "greater-than +sign" (U+003E, >), "plus sign" (U+002B, ++) and "tilde" (U+007E, ~). White +space may appear between a combinator and the simple selectors around +it. Only the characters "space" (U+0020), "tab" +(U+0009), "line feed" (U+000A), "carriage return" (U+000D), and "form +feed" (U+000C) can occur in white space. Other space-like characters, +such as "em-space" (U+2003) and "ideographic space" (U+3000), are +never part of white space.

+ +

The elements of a document tree that are represented by a selector +are the subjects of the selector. A +selector consisting of a single sequence of simple selectors +represents any element satisfying its requirements. Prepending another +sequence of simple selectors and a combinator to a sequence imposes +additional matching constraints, so the subjects of a selector are +always a subset of the elements represented by the last sequence of +simple selectors.

+ +

An empty selector, containing no sequence of simple selectors and +no pseudo-element, is an invalid +selector.

+ +

5. Groups of selectors

+ +

When several selectors share the same declarations, they may be +grouped into a comma-separated list. (A comma is U+002C.)

+ +
+

CSS examples:

+

In this example, we condense three rules with identical +declarations into one. Thus,

+
h1 { font-family: sans-serif }
+h2 { font-family: sans-serif }
+h3 { font-family: sans-serif }
+

is equivalent to:

+
h1, h2, h3 { font-family: sans-serif }
+
+ +

Warning: the equivalence is true in this example +because all the selectors are valid selectors. If just one of these +selectors were invalid, the entire group of selectors would be +invalid. This would invalidate the rule for all three heading +elements, whereas in the former case only one of the three individual +heading rules would be invalidated.

+ + +

6. Simple selectors

+ +

6.1. Type selector

+ +

A type selector is the name of a document language +element type. A type selector represents an instance of the element +type in the document tree.

+ +
+

Example:

+

The following selector represents an h1 element in the document tree:

+
h1
+
+ + +

6.1.1. Type selectors and namespaces

+ +

Type selectors allow an optional namespace ([XMLNAMES]) component. A namespace prefix +that has been previously declared may be prepended to the element name +separated by the namespace separator "vertical bar" +(U+007C, |).

+ +

The namespace component may be left empty to indicate that the +selector is only to represent elements with no declared namespace.

+ +

An asterisk may be used for the namespace prefix, indicating that +the selector represents elements in any namespace (including elements +with no namespace).

+ +

Element type selectors that have no namespace component (no +namespace separator), represent elements without regard to the +element's namespace (equivalent to "*|") unless a default +namespace has been declared. If a default namespace has been declared, +the selector will represent only elements in the default +namespace.

+ +

A type selector containing a namespace prefix that has not been +previously declared is an invalid selector. +The mechanism for declaring a namespace prefix is left up to the +language implementing Selectors. In CSS, such a mechanism is defined +in the General Syntax module.

+ +

In a namespace-aware client, element type selectors will only match +against the local part +of the element's qualified +name. See below for notes about matching +behaviors in down-level clients.

+ +

In summary:

+ +
+
ns|E
+
elements with name E in namespace ns
+
*|E
+
elements with name E in any namespace, including those without any + declared namespace
+
|E
+
elements with name E without any declared namespace
+
E
+
if no default namespace has been specified, this is equivalent to *|E. + Otherwise it is equivalent to ns|E where ns is the default namespace.
+
+ +
+

CSS examples:

+ +
@namespace foo url(http://www.example.com);
+ foo|h1 { color: blue }
+ foo|* { color: yellow }
+ |h1 { color: red }
+ *|h1 { color: green }
+ h1 { color: green }
+ +

The first rule will match only h1 elements in the + "http://www.example.com" namespace.

+ +

The second rule will match all elements in the + "http://www.example.com" namespace.

+ +

The third rule will match only h1 elements without + any declared namespace.

+ +

The fourth rule will match h1 elements in any + namespace (including those without any declared namespace).

+ +

The last rule is equivalent to the fourth rule because no default + namespace has been defined.

+ +
+ +

6.2. Universal selector

+ +

The universal selector, written "asterisk" +(*), represents the qualified name of any element +type. It represents any single element in the document tree in any +namespace (including those without any declared namespace) if no +default namespace has been specified. If a default namespace has been +specified, see Universal selector and +Namespaces below.

+ +

If the universal selector is not the only component of a sequence +of simple selectors, the * may be omitted.

+ +
+

Examples:

+
    +
  • *[hreflang|=en] and [hreflang|=en] are equivalent,
  • +
  • *.warning and .warning are equivalent,
  • +
  • *#myid and #myid are equivalent.
  • +
+
+ +

Note: it is recommended that the +*, representing the universal selector, not be +omitted.

+ +

6.2.1. Universal selector and namespaces

+ +

The universal selector allows an optional namespace component. It +is used as follows:

+ +
+
ns|*
+
all elements in namespace ns
+
*|*
+
all elements
+
|*
+
all elements without any declared namespace
+
*
+
if no default namespace has been specified, this is equivalent to *|*. + Otherwise it is equivalent to ns|* where ns is the default namespace.
+
+ +

A universal selector containing a namespace prefix that has not +been previously declared is an invalid +selector. The mechanism for declaring a namespace prefix is left up +to the language implementing Selectors. In CSS, such a mechanism is +defined in the General Syntax module.

+ + +

6.3. Attribute selectors

+ +

Selectors allow the representation of an element's attributes. When +a selector is used as an expression to match against an element, +attribute selectors must be considered to match an element if that +element has an attribute that matches the attribute represented by the +attribute selector.

+ +

6.3.1. Attribute presence and values +selectors

+ +

CSS2 introduced four attribute selectors:

+ +
+
[att] +
Represents an element with the att attribute, whatever the value of + the attribute.
+
[att=val]
+
Represents an element with the att attribute whose value is exactly + "val".
+
[att~=val]
+
Represents an element with the att attribute whose value is a whitespace-separated list of words, one of + which is exactly "val". If "val" contains whitespace, it will never + represent anything (since the words are separated by + spaces).
+
[att|=val] +
Represents an element with the att attribute, its value either + being exactly "val" or beginning with "val" immediately followed by + "-" (U+002D). This is primarily intended to allow language subcode + matches (e.g., the hreflang attribute on the + link element in HTML) as described in RFC 3066 ([RFC3066]). For lang (or + xml:lang) language subcode matching, please see the :lang pseudo-class.
+
+ +

Attribute values must be identifiers or strings. The +case-sensitivity of attribute names and values in selectors depends on +the document language.

+ +
+ +

Examples:

+ +

The following attribute selector represents an h1 + element that carries the title attribute, whatever its + value:

+ +
h1[title]
+ +

In the following example, the selector represents a + span element whose class attribute has + exactly the value "example":

+ +
span[class="example"]
+ +

Multiple attribute selectors can be used to represent several + attributes of an element, or several conditions on the same + attribute. Here, the selector represents a span element + whose hello attribute has exactly the value "Cleveland" + and whose goodbye attribute has exactly the value + "Columbus":

+ +
span[hello="Cleveland"][goodbye="Columbus"]
+ +

The following selectors illustrate the differences between "=" + and "~=". The first selector will represent, for example, the value + "copyright copyleft copyeditor" on a rel attribute. The + second selector will only represent an a element with + an href attribute having the exact value + "http://www.w3.org/".

+ +
a[rel~="copyright"]
+a[href="http://www.w3.org/"]
+ +

The following selector represents a link element + whose hreflang attribute is exactly "fr".

+ +
link[hreflang=fr]
+ +

The following selector represents a link element for + which the values of the hreflang attribute begins with + "en", including "en", "en-US", and "en-cockney":

+ +
link[hreflang|="en"]
+ +

Similarly, the following selectors represents a + DIALOGUE element whenever it has one of two different + values for an attribute character:

+ +
DIALOGUE[character=romeo]
+DIALOGUE[character=juliet]
+ +
+ +

6.3.2. Substring matching attribute +selectors

+ +

Three additional attribute selectors are provided for matching +substrings in the value of an attribute:

+ +
+
[att^=val]
+
Represents an element with the att attribute whose value begins + with the prefix "val".
+
[att$=val] +
Represents an element with the att attribute whose value ends with + the suffix "val".
+
[att*=val] +
Represents an element with the att attribute whose value contains + at least one instance of the substring "val".
+
+ +

Attribute values must be identifiers or strings. The +case-sensitivity of attribute names in selectors depends on the +document language.

+ +
+

Examples:

+

The following selector represents an HTML object, referencing an + image:

+
object[type^="image/"]
+

The following selector represents an HTML anchor a with an + href attribute whose value ends with ".html".

+
a[href$=".html"]
+

The following selector represents an HTML paragraph with a title + attribute whose value contains the substring "hello"

+
p[title*="hello"]
+
+ +

6.3.3. Attribute selectors and namespaces

+ +

Attribute selectors allow an optional namespace component to the +attribute name. A namespace prefix that has been previously declared +may be prepended to the attribute name separated by the namespace +separator "vertical bar" (|). In keeping with +the Namespaces in the XML recommendation, default namespaces do not +apply to attributes, therefore attribute selectors without a namespace +component apply only to attributes that have no declared namespace +(equivalent to "|attr"). An asterisk may be used for the +namespace prefix indicating that the selector is to match all +attribute names without regard to the attribute's namespace. + +

An attribute selector with an attribute name containing a namespace +prefix that has not been previously declared is an invalid selector. The mechanism for declaring +a namespace prefix is left up to the language implementing Selectors. +In CSS, such a mechanism is defined in the General Syntax module. + +

+

CSS examples:

+
@namespace foo "http://www.example.com";
+[foo|att=val] { color: blue }
+[*|att] { color: yellow }
+[|att] { color: green }
+[att] { color: green }
+ +

The first rule will match only elements with the attribute + att in the "http://www.example.com" namespace with the + value "val".

+ +

The second rule will match only elements with the attribute + att regardless of the namespace of the attribute + (including no declared namespace).

+ +

The last two rules are equivalent and will match only elements + with the attribute att where the attribute is not + declared to be in a namespace.

+ +
+ +

6.3.4. Default attribute values in DTDs

+ +

Attribute selectors represent explicitly set attribute values in +the document tree. Default attribute values may be defined in a DTD or +elsewhere, but cannot always be selected by attribute +selectors. Selectors should be designed so that they work even if the +default values are not included in the document tree.

+ +

More precisely, a UA is not required to read an "external +subset" of the DTD but is required to look for default +attribute values in the document's "internal subset." (See [XML10] for definitions of these subsets.)

+ +

A UA that recognizes an XML namespace [XMLNAMES] is not required to use its +knowledge of that namespace to treat default attribute values as if +they were present in the document. (For example, an XHTML UA is not +required to use its built-in knowledge of the XHTML DTD.)

+ +

Note: Typically, implementations +choose to ignore external subsets.

+ +
+

Example:

+ +

Consider an element EXAMPLE with an attribute "notation" that has a +default value of "decimal". The DTD fragment might be

+ +
<!ATTLIST EXAMPLE notation (decimal,octal) "decimal">
+ +

If the style sheet contains the rules

+ +
EXAMPLE[notation=decimal] { /*... default property settings ...*/ }
+EXAMPLE[notation=octal]   { /*... other settings...*/ }
+ +

the first rule will not match elements whose "notation" attribute +is set by default, i.e. not set explicitly. To catch all cases, the +attribute selector for the default value must be dropped:

+ +
EXAMPLE                   { /*... default property settings ...*/ }
+EXAMPLE[notation=octal]   { /*... other settings...*/ }
+ +

Here, because the selector EXAMPLE[notation=octal] is +more specific than the tag +selector alone, the style declarations in the second rule will override +those in the first for elements that have a "notation" attribute value +of "octal". Care has to be taken that all property declarations that +are to apply only to the default case are overridden in the non-default +cases' style rules.

+ +
+ +

6.4. Class selectors

+ +

Working with HTML, authors may use the period (U+002E, +.) notation as an alternative to the ~= +notation when representing the class attribute. Thus, for +HTML, div.value and div[class~=value] have +the same meaning. The attribute value must immediately follow the +"period" (.).

+ +

UAs may apply selectors using the period (.) notation in XML +documents if the UA has namespace-specific knowledge that allows it to +determine which attribute is the "class" attribute for the +respective namespace. One such example of namespace-specific knowledge +is the prose in the specification for a particular namespace (e.g. SVG +1.0 [SVG] describes the SVG +"class" attribute and how a UA should interpret it, and +similarly MathML 1.01 [MATH] describes the MathML +"class" attribute.)

+ +
+

CSS examples:

+ +

We can assign style information to all elements with + class~="pastoral" as follows:

+ +
*.pastoral { color: green }  /* all elements with class~=pastoral */
+ +

or just

+ +
.pastoral { color: green }  /* all elements with class~=pastoral */
+ +

The following assigns style only to H1 elements with + class~="pastoral":

+ +
H1.pastoral { color: green }  /* H1 elements with class~=pastoral */
+ +

Given these rules, the first H1 instance below would not have + green text, while the second would:

+ +
<H1>Not green</H1>
+<H1 class="pastoral">Very green</H1>
+ +
+ +

To represent a subset of "class" values, each value must be preceded +by a ".", in any order.

+ +
+ +

CSS example:

+ +

The following rule matches any P element whose "class" attribute + has been assigned a list of whitespace-separated values that includes + "pastoral" and "marine":

+ +
p.pastoral.marine { color: green }
+ +

This rule matches when class="pastoral blue aqua + marine" but does not match for class="pastoral + blue".

+ +
+ +

Note: Because CSS gives considerable +power to the "class" attribute, authors could conceivably design their +own "document language" based on elements with almost no associated +presentation (such as DIV and SPAN in HTML) and assigning style +information through the "class" attribute. Authors should avoid this +practice since the structural elements of a document language often +have recognized and accepted meanings and author-defined classes may +not.

+ +

Note: If an element has multiple +class attributes, their values must be concatenated with spaces +between the values before searching for the class. As of this time the +working group is not aware of any manner in which this situation can +be reached, however, so this behavior is explicitly non-normative in +this specification.

+ +

6.5. ID selectors

+ +

Document languages may contain attributes that are declared to be +of type ID. What makes attributes of type ID special is that no two +such attributes can have the same value in a document, regardless of +the type of the elements that carry them; whatever the document +language, an ID typed attribute can be used to uniquely identify its +element. In HTML all ID attributes are named "id"; XML applications +may name ID attributes differently, but the same restriction +applies.

+ +

An ID-typed attribute of a document language allows authors to +assign an identifier to one element instance in the document tree. W3C +ID selectors represent an element instance based on its identifier. An +ID selector contains a "number sign" (U+0023, +#) immediately followed by the ID value, which must be an +identifier.

+ +

Selectors does not specify how a UA knows the ID-typed attribute of +an element. The UA may, e.g., read a document's DTD, have the +information hard-coded or ask the user. + +

+

Examples:

+

The following ID selector represents an h1 element + whose ID-typed attribute has the value "chapter1":

+
h1#chapter1
+

The following ID selector represents any element whose ID-typed + attribute has the value "chapter1":

+
#chapter1
+

The following selector represents any element whose ID-typed + attribute has the value "z98y".

+
*#z98y
+
+ +

Note. In XML 1.0 [XML10], the information about which attribute +contains an element's IDs is contained in a DTD or a schema. When +parsing XML, UAs do not always read the DTD, and thus may not know +what the ID of an element is (though a UA may have namespace-specific +knowledge that allows it to determine which attribute is the ID +attribute for that namespace). If a style sheet designer knows or +suspects that a UA may not know what the ID of an element is, he +should use normal attribute selectors instead: +[name=p371] instead of #p371. Elements in +XML 1.0 documents without a DTD do not have IDs at all.

+ +

If an element has multiple ID attributes, all of them must be +treated as IDs for that element for the purposes of the ID +selector. Such a situation could be reached using mixtures of xml:id, +DOM3 Core, XML DTDs, and namespace-specific knowledge.

+ +

6.6. Pseudo-classes

+ +

The pseudo-class concept is introduced to permit selection based on +information that lies outside of the document tree or that cannot be +expressed using the other simple selectors.

+ +

A pseudo-class always consists of a "colon" +(:) followed by the name of the pseudo-class and +optionally by a value between parentheses.

+ +

Pseudo-classes are allowed in all sequences of simple selectors +contained in a selector. Pseudo-classes are allowed anywhere in +sequences of simple selectors, after the leading type selector or +universal selector (possibly omitted). Pseudo-class names are +case-insensitive. Some pseudo-classes are mutually exclusive, while +others can be applied simultaneously to the same +element. Pseudo-classes may be dynamic, in the sense that an element +may acquire or lose a pseudo-class while a user interacts with the +document.

+ + +

6.6.1. Dynamic pseudo-classes

+ +

Dynamic pseudo-classes classify elements on characteristics other +than their name, attributes, or content, in principle characteristics +that cannot be deduced from the document tree.

+ +

Dynamic pseudo-classes do not appear in the document source or +document tree.

+ + +
The link pseudo-classes: :link and :visited
+ +

User agents commonly display unvisited links differently from +previously visited ones. Selectors +provides the pseudo-classes :link and +:visited to distinguish them:

+ + + +

After some amount of time, user agents may choose to return a +visited link to the (unvisited) ':link' state.

+ +

The two states are mutually exclusive.

+ +
+ +

Example:

+ +

The following selector represents links carrying class + external and already visited:

+ +
a.external:visited
+ +
+ +

Note: It is possible for style sheet +authors to abuse the :link and :visited pseudo-classes to determine +which sites a user has visited without the user's consent. + +

UAs may therefore treat all links as unvisited links, or implement +other measures to preserve the user's privacy while rendering visited +and unvisited links differently.

+ +
The user action pseudo-classes +:hover, :active, and :focus
+ +

Interactive user agents sometimes change the rendering in response +to user actions. Selectors provides +three pseudo-classes for the selection of an element the user is +acting on.

+ + + +

There may be document language or implementation specific limits on +which elements can become :active or acquire +:focus.

+ +

These pseudo-classes are not mutually exclusive. An element may +match several pseudo-classes at the same time.

+ +

Selectors doesn't define if the parent of an element that is +':active' or ':hover' is also in that state.

+ +
+

Examples:

+
a:link    /* unvisited links */
+a:visited /* visited links */
+a:hover   /* user hovers */
+a:active  /* active links */
+

An example of combining dynamic pseudo-classes:

+
a:focus
+a:focus:hover
+

The last selector matches a elements that are in + the pseudo-class :focus and in the pseudo-class :hover.

+
+ +

Note: An element can be both ':visited' +and ':active' (or ':link' and ':active').

+ +

6.6.2. The target pseudo-class :target

+ +

Some URIs refer to a location within a resource. This kind of URI +ends with a "number sign" (#) followed by an anchor +identifier (called the fragment identifier).

+ +

URIs with fragment identifiers link to a certain element within the +document, known as the target element. For instance, here is a URI +pointing to an anchor named section_2 in an HTML +document:

+ +
http://example.com/html/top.html#section_2
+ +

A target element can be represented by the :target +pseudo-class. If the document's URI has no fragment identifier, then +the document has no target element.

+ +
+

Example:

+
p.note:target
+

This selector represents a p element of class + note that is the target element of the referring + URI.

+
+ +
+

CSS example:

+

Here, the :target pseudo-class is used to make the + target element red and place an image before it, if there is one:

+
*:target { color : red }
+*:target::before { content : url(target.png) }
+
+ +

6.6.3. The language pseudo-class :lang

+ +

If the document language specifies how the human language of an +element is determined, it is possible to write selectors that +represent an element based on its language. For example, in HTML [HTML4], the language is determined by a +combination of the lang attribute, the meta +element, and possibly by information from the protocol (such as HTTP +headers). XML uses an attribute called xml:lang, and +there may be other document language-specific methods for determining +the language.

+ +

The pseudo-class :lang(C) represents an element that +is in language C. Whether an element is represented by a +:lang() selector is based solely on the identifier C +being either equal to, or a hyphen-separated substring of, the +element's language value, in the same way as if performed by the '|=' operator in attribute +selectors. The identifier C does not have to be a valid language +name.

+ +

C must not be empty. (If it is, the selector is invalid.)

+ +

Note: It is recommended that +documents and protocols indicate language using codes from RFC 3066 [RFC3066] or its successor, and by means of +"xml:lang" attributes in the case of XML-based documents [XML10]. See +"FAQ: Two-letter or three-letter language codes."

+ +
+

Examples:

+

The two following selectors represent an HTML document that is in + Belgian, French, or German. The two next selectors represent + q quotations in an arbitrary element in Belgian, French, + or German.

+
html:lang(fr-be)
+html:lang(de)
+:lang(fr-be) > q
+:lang(de) > q
+
+ +

6.6.4. The UI element states pseudo-classes

+ +
The :enabled and :disabled pseudo-classes
+ +

The :enabled pseudo-class allows authors to customize +the look of user interface elements that are enabled — which the +user can select or activate in some fashion (e.g. clicking on a button +with a mouse). There is a need for such a pseudo-class because there +is no way to programmatically specify the default appearance of say, +an enabled input element without also specifying what it +would look like when it was disabled.

+ +

Similar to :enabled, :disabled allows the +author to specify precisely how a disabled or inactive user interface +element should look.

+ +

Most elements will be neither enabled nor disabled. An element is +enabled if the user can either activate it or transfer the focus to +it. An element is disabled if it could be enabled, but the user cannot +presently activate it or transfer focus to it.

+ + +
The :checked pseudo-class
+ +

Radio and checkbox elements can be toggled by the user. Some menu +items are "checked" when the user selects them. When such elements are +toggled "on" the :checked pseudo-class applies. The +:checked pseudo-class initially applies to such elements +that have the HTML4 selected and checked +attributes as described in Section +17.2.1 of HTML4, but of course the user can toggle "off" such +elements in which case the :checked pseudo-class would no +longer apply. While the :checked pseudo-class is dynamic +in nature, and is altered by user action, since it can also be based +on the presence of the semantic HTML4 selected and +checked attributes, it applies to all media. + + +

The :indeterminate pseudo-class
+ +
+ +

Radio and checkbox elements can be toggled by the user, but are +sometimes in an indeterminate state, neither checked nor unchecked. +This can be due to an element attribute, or DOM manipulation.

+ +

A future version of this specification may introduce an +:indeterminate pseudo-class that applies to such elements. +

+ +
+ + +

6.6.5. Structural pseudo-classes

+ +

Selectors introduces the concept of structural +pseudo-classes to permit selection based on extra information that lies in +the document tree but cannot be represented by other simple selectors or +combinators. + +

Note that standalone pieces of PCDATA (text nodes in the DOM) are +not counted when calculating the position of an element in the list of +children of its parent. When calculating the position of an element in +the list of children of its parent, the index numbering starts at 1. + + +

:root pseudo-class
+ +

The :root pseudo-class represents an element that is +the root of the document. In HTML 4, this is always the +HTML element. + + +

:nth-child() pseudo-class
+ +

The +:nth-child(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings +before it in the document tree, for a given positive +integer or zero value of n, and has a parent element. In +other words, this matches the bth child of an element after +all the children have been split into groups of a elements +each. For example, this allows the selectors to address every other +row in a table, and could be used to alternate the color +of paragraph text in a cycle of four. The a and +b values must be zero, negative integers or positive +integers. The index of the first child of an element is 1. + +

In addition to this, :nth-child() can take +'odd' and 'even' as arguments instead. +'odd' has the same signification as 2n+1, +and 'even' has the same signification as 2n. + + +

+

Examples:

+
tr:nth-child(2n+1) /* represents every odd row of an HTML table */
+tr:nth-child(odd)  /* same */
+tr:nth-child(2n)   /* represents every even row of an HTML table */
+tr:nth-child(even) /* same */
+
+/* Alternate paragraph colours in CSS */
+p:nth-child(4n+1) { color: navy; }
+p:nth-child(4n+2) { color: green; }
+p:nth-child(4n+3) { color: maroon; }
+p:nth-child(4n+4) { color: purple; }
+
+ +

When a=0, no repeating is used, so for example +:nth-child(0n+5) matches only the fifth child. When +a=0, the an part need not be +included, so the syntax simplifies to +:nth-child(b) and the last example simplifies +to :nth-child(5). + +

+

Examples:

+
foo:nth-child(0n+1)   /* represents an element foo, first child of its parent element */
+foo:nth-child(1)      /* same */
+
+ +

When a=1, the number may be omitted from the rule. + +

+

Examples:

+

The following selectors are therefore equivalent:

+
bar:nth-child(1n+0)   /* represents all bar elements, specificity (0,1,1) */
+bar:nth-child(n+0)    /* same */
+bar:nth-child(n)      /* same */
+bar                   /* same but lower specificity (0,0,1) */
+
+ +

If b=0, then every ath element is picked. In +such a case, the b part may be omitted. + +

+

Examples:

+
tr:nth-child(2n+0) /* represents every even row of an HTML table */
+tr:nth-child(2n) /* same */
+
+ +

If both a and b are equal to zero, the +pseudo-class represents no element in the document tree.

+ +

The value a can be negative, but only the positive +values of an+b, for +n≥0, may represent an element in the document +tree.

+ +
+

Example:

+
html|tr:nth-child(-n+6)  /* represents the 6 first rows of XHTML tables */
+
+ +

When the value b is negative, the "+" character in the +expression must be removed (it is effectively replaced by the "-" +character indicating the negative value of b).

+ +
+

Examples:

+
:nth-child(10n-1)  /* represents the 9th, 19th, 29th, etc, element */
+:nth-child(10n+9)  /* Same */
+:nth-child(10n+-1) /* Syntactically invalid, and would be ignored */
+
+ + +
:nth-last-child() pseudo-class
+ +

The :nth-last-child(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings +after it in the document tree, for a given positive +integer or zero value of n, and has a parent element. See +:nth-child() pseudo-class for the syntax of its argument. +It also accepts the 'even' and 'odd' values +as arguments. + + +

+

Examples:

+
tr:nth-last-child(-n+2)    /* represents the two last rows of an HTML table */
+
+foo:nth-last-child(odd)    /* represents all odd foo elements in their parent element,
+                              counting from the last one */
+
+ + +
:nth-of-type() pseudo-class
+ +

The :nth-of-type(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings with the same +element name before it in the document tree, for a +given zero or positive integer value of n, and has a +parent element. In other words, this matches the bth child +of that type after all the children of that type have been split into +groups of a elements each. See :nth-child() pseudo-class +for the syntax of its argument. It also accepts the +'even' and 'odd' values. + + +

+

CSS example:

+

This allows an author to alternate the position of floated images:

+
img:nth-of-type(2n+1) { float: right; }
+img:nth-of-type(2n) { float: left; }
+
+ + +
:nth-last-of-type() pseudo-class
+ +

The :nth-last-of-type(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings with the same +element name after it in the document tree, for a +given zero or positive integer value of n, and has a +parent element. See :nth-child() pseudo-class for the +syntax of its argument. It also accepts the 'even' and 'odd' values. + + +

+

Example:

+

To represent all h2 children of an XHTML + body except the first and last, one could use the + following selector:

+
body > h2:nth-of-type(n+2):nth-last-of-type(n+2)
+

In this case, one could also use :not(), although the + selector ends up being just as long:

+
body > h2:not(:first-of-type):not(:last-of-type)
+
+ + +
:first-child pseudo-class
+ +

Same as :nth-child(1). The :first-child pseudo-class +represents an element that is the first child of some other element. + + +

+

Examples:

+

The following selector represents a p element that is + the first child of a div element:

+
div > p:first-child
+

This selector can represent the p inside the + div of the following fragment:

+
<p> The last P before the note.</p>
+<div class="note">
+   <p> The first P inside the note.</p>
+</div>
but cannot represent the second p in the following +fragment: +
<p> The last P before the note.</p>
+<div class="note">
+   <h2> Note </h2>
+   <p> The first P inside the note.</p>
+</div>
+

The following two selectors are usually equivalent:

+
* > a:first-child /* a is first child of any element */
+a:first-child /* Same (assuming a is not the root element) */
+
+ +
:last-child pseudo-class
+ +

Same as :nth-last-child(1). The :last-child pseudo-class +represents an element that is the last child of some other element. + +

+

Example:

+

The following selector represents a list item li that + is the last child of an ordered list ol. +

ol > li:last-child
+
+ +
:first-of-type pseudo-class
+ +

Same as :nth-of-type(1). The :first-of-type pseudo-class +represents an element that is the first sibling of its type in the list of +children of its parent element. + +

+

Example:

+

The following selector represents a definition title +dt inside a definition list dl, this +dt being the first of its type in the list of children of +its parent element.

+
dl dt:first-of-type
+

It is a valid description for the first two dt +elements in the following example but not for the third one:

+
<dl>
+ <dt>gigogne</dt>
+ <dd>
+  <dl>
+   <dt>fusée</dt>
+   <dd>multistage rocket</dd>
+   <dt>table</dt>
+   <dd>nest of tables</dd>
+  </dl>
+ </dd>
+</dl>
+
+ +
:last-of-type pseudo-class
+ +

Same as :nth-last-of-type(1). The +:last-of-type pseudo-class represents an element that is +the last sibling of its type in the list of children of its parent +element.

+ +
+

Example:

+

The following selector represents the last data cell + td of a table row.

+
tr > td:last-of-type
+
+ +
:only-child pseudo-class
+ +

Represents an element that has a parent element and whose parent +element has no other element children. Same as +:first-child:last-child or +:nth-child(1):nth-last-child(1), but with a lower +specificity.

+ +
:only-of-type pseudo-class
+ +

Represents an element that has a parent element and whose parent +element has no other element children with the same element name. Same +as :first-of-type:last-of-type or +:nth-of-type(1):nth-last-of-type(1), but with a lower +specificity.

+ + +
:empty pseudo-class
+ +

The :empty pseudo-class represents an element that has +no children at all. In terms of the DOM, only element nodes and text +nodes (including CDATA nodes and entity references) whose data has a +non-zero length must be considered as affecting emptiness; comments, +PIs, and other nodes must not affect whether an element is considered +empty or not.

+ +
+

Examples:

+

p:empty is a valid representation of the following fragment:

+
<p></p>
+

foo:empty is not a valid representation for the + following fragments:

+
<foo>bar</foo>
+
<foo><bar>bla</bar></foo>
+
<foo>this is not <bar>:empty</bar></foo>
+
+ +

6.6.6. Blank

+ +

This section intentionally left blank.

+ + +

6.6.7. The negation pseudo-class

+ +

The negation pseudo-class, :not(X), is a +functional notation taking a simple +selector (excluding the negation pseudo-class itself and +pseudo-elements) as an argument. It represents an element that is not +represented by the argument. + + + +

+

Examples:

+

The following CSS selector matches all button + elements in an HTML document that are not disabled.

+
button:not([DISABLED])
+

The following selector represents all but FOO + elements.

+
*:not(FOO)
+

The following group of selectors represents all HTML elements + except links.

+
html|*:not(:link):not(:visited)
+
+ +

Default namespace declarations do not affect the argument of the +negation pseudo-class unless the argument is a universal selector or a +type selector.

+ +
+

Examples:

+

Assuming that the default namespace is bound to + "http://example.com/", the following selector represents all + elements that are not in that namespace:

+
*|*:not(*)
+

The following CSS selector matches any element being hovered, + regardless of its namespace. In particular, it is not limited to + only matching elements in the default namespace that are not being + hovered, and elements not in the default namespace don't match the + rule when they are being hovered.

+
*|*:not(:hover)
+
+ +

Note: the :not() pseudo allows +useless selectors to be written. For instance :not(*|*), +which represents no element at all, or foo:not(bar), +which is equivalent to foo but with a higher +specificity.

+ +

7. Pseudo-elements

+ +

Pseudo-elements create abstractions about the document tree beyond +those specified by the document language. For instance, document +languages do not offer mechanisms to access the first letter or first +line of an element's content. Pseudo-elements allow designers to refer +to this otherwise inaccessible information. Pseudo-elements may also +provide designers a way to refer to content that does not exist in the +source document (e.g., the ::before and +::after pseudo-elements give access to generated +content).

+ +

A pseudo-element is made of two colons (::) followed +by the name of the pseudo-element.

+ +

This :: notation is introduced by the current document +in order to establish a discrimination between pseudo-classes and +pseudo-elements. For compatibility with existing style sheets, user +agents must also accept the previous one-colon notation for +pseudo-elements introduced in CSS levels 1 and 2 (namely, +:first-line, :first-letter, +:before and :after). This compatibility is +not allowed for the new pseudo-elements introduced in CSS level 3.

+ +

Only one pseudo-element may appear per selector, and if present it +must appear after the sequence of simple selectors that represents the +subjects of the selector. A +future version of this specification may allow multiple +pesudo-elements per selector.

+ +

7.1. The ::first-line pseudo-element

+ +

The ::first-line pseudo-element describes the contents +of the first formatted line of an element. + +

+

CSS example:

+
p::first-line { text-transform: uppercase }
+

The above rule means "change the letters of the first line of every +paragraph to uppercase".

+
+ +

The selector p::first-line does not match any real +HTML element. It does match a pseudo-element that conforming user +agents will insert at the beginning of every paragraph.

+ +

Note that the length of the first line depends on a number of +factors, including the width of the page, the font size, etc. Thus, +an ordinary HTML paragraph such as:

+ +
+<P>This is a somewhat long HTML 
+paragraph that will be broken into several 
+lines. The first line will be identified
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

the lines of which happen to be broken as follows: + +

+THIS IS A SOMEWHAT LONG HTML PARAGRAPH THAT
+will be broken into several lines. The first
+line will be identified by a fictional tag 
+sequence. The other lines will be treated as 
+ordinary lines in the paragraph.
+
+ +

This paragraph might be "rewritten" by user agents to include the +fictional tag sequence for ::first-line. This +fictional tag sequence helps to show how properties are inherited.

+ +
+<P><P::first-line> This is a somewhat long HTML 
+paragraph that </P::first-line> will be broken into several
+lines. The first line will be identified 
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

If a pseudo-element breaks up a real element, the desired effect +can often be described by a fictional tag sequence that closes and +then re-opens the element. Thus, if we mark up the previous paragraph +with a span element:

+ +
+<P><SPAN class="test"> This is a somewhat long HTML
+paragraph that will be broken into several
+lines.</SPAN> The first line will be identified
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

the user agent could simulate start and end tags for +span when inserting the fictional tag sequence for +::first-line. + +

+<P><P::first-line><SPAN class="test"> This is a
+somewhat long HTML
+paragraph that will </SPAN></P::first-line><SPAN class="test"> be
+broken into several
+lines.</SPAN> The first line will be identified
+by a fictional tag sequence. The other lines
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

In CSS, the ::first-line pseudo-element can only be +attached to a block-level element, an inline-block, a table-caption, +or a table-cell.

+ +

The "first formatted line" of an +element may occur inside a +block-level descendant in the same flow (i.e., a block-level +descendant that is not positioned and not a float). E.g., the first +line of the div in <DIV><P>This +line...</P></DIV> is the first line of the p (assuming +that both p and div are block-level). + +

The first line of a table-cell or inline-block cannot be the first +formatted line of an ancestor element. Thus, in <DIV><P +STYLE="display: inline-block">Hello<BR>Goodbye</P> +etcetera</DIV> the first formatted line of the +div is not the line "Hello". + +

Note that the first line of the p in this +fragment: <p><br>First... doesn't contain any +letters (assuming the default style for br in HTML +4). The word "First" is not on the first formatted line. + +

A UA should act as if the fictional start tags of the +::first-line pseudo-elements were nested just inside the +innermost enclosing block-level element. (Since CSS1 and CSS2 were +silent on this case, authors should not rely on this behavior.) Here +is an example. The fictional tag sequence for

+ +
+<DIV>
+  <P>First paragraph</P>
+  <P>Second paragraph</P>
+</DIV>
+
+ +

is

+ +
+<DIV>
+  <P><DIV::first-line><P::first-line>First paragraph</P::first-line></DIV::first-line></P>
+  <P><P::first-line>Second paragraph</P::first-line></P>
+</DIV>
+
+ +

The ::first-line pseudo-element is similar to an +inline-level element, but with certain restrictions. In CSS, the +following properties apply to a ::first-line +pseudo-element: font properties, color property, background +properties, 'word-spacing', 'letter-spacing', 'text-decoration', +'vertical-align', 'text-transform', 'line-height'. UAs may apply other +properties as well.

+ + +

7.2. The ::first-letter pseudo-element

+ +

The ::first-letter pseudo-element represents the first +letter of the first line of a block, if it is not preceded by any +other content (such as images or inline tables) on its line. The +::first-letter pseudo-element may be used for "initial caps" and "drop +caps", which are common typographical effects. This type of initial +letter is similar to an inline-level element if its 'float' property +is 'none'; otherwise, it is similar to a floated element.

+ +

In CSS, these are the properties that apply to ::first-letter +pseudo-elements: font properties, 'text-decoration', 'text-transform', +'letter-spacing', 'word-spacing' (when appropriate), 'line-height', +'float', 'vertical-align' (only if 'float' is 'none'), margin +properties, padding properties, border properties, color property, +background properties. UAs may apply other properties as well. To +allow UAs to render a typographically correct drop cap or initial cap, +the UA may choose a line-height, width and height based on the shape +of the letter, unlike for normal elements.

+ +
+

Example:

+

This example shows a possible rendering of an initial cap. Note +that the 'line-height' that is inherited by the ::first-letter +pseudo-element is 1.1, but the UA in this example has computed the +height of the first letter differently, so that it doesn't cause any +unnecessary space between the first two lines. Also note that the +fictional start tag of the first letter is inside the span, and thus +the font weight of the first letter is normal, not bold as the span: +

+p { line-height: 1.1 }
+p::first-letter { font-size: 3em; font-weight: normal }
+span { font-weight: bold }
+...
+<p><span>Het hemelsche</span> gerecht heeft zich ten lange lesten<br>
+Erbarremt over my en mijn benaeuwde vesten<br>
+En arme burgery, en op mijn volcx gebed<br>
+En dagelix geschrey de bange stad ontzet.
+
+
+

Image illustrating the ::first-letter pseudo-element +

+
+ +
+

The following CSS will make a drop cap initial letter span about two lines:

+ +
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<HTML>
+ <HEAD>
+  <TITLE>Drop cap initial letter</TITLE>
+  <STYLE type="text/css">
+   P               { font-size: 12pt; line-height: 1.2 }
+   P::first-letter { font-size: 200%; font-weight: bold; float: left }
+   SPAN            { text-transform: uppercase }
+  </STYLE>
+ </HEAD>
+ <BODY>
+  <P><SPAN>The first</SPAN> few words of an article
+    in The Economist.</P>
+ </BODY>
+</HTML>
+
+ +

This example might be formatted as follows:

+ +
+

Image illustrating the combined effect of the ::first-letter and ::first-line pseudo-elements

+
+ +

The fictional tag sequence is:

+ +
+<P>
+<SPAN>
+<P::first-letter>
+T
+</P::first-letter>he first
+</SPAN> 
+few words of an article in the Economist.
+</P>
+
+ +

Note that the ::first-letter pseudo-element tags abut +the content (i.e., the initial character), while the ::first-line +pseudo-element start tag is inserted right after the start tag of the +block element.

+ +

In order to achieve traditional drop caps formatting, user agents +may approximate font sizes, for example to align baselines. Also, the +glyph outline may be taken into account when formatting.

+ +

Punctuation (i.e, characters defined in Unicode in the "open" (Ps), +"close" (Pe), "initial" (Pi). "final" (Pf) and "other" (Po) +punctuation classes), that precedes or follows the first letter should +be included. [UNICODE]

+ +
+

Quotes that precede the
+first letter should be included.

+
+ +

The ::first-letter also applies if the first letter is +in fact a digit, e.g., the "6" in "67 million dollars is a lot of +money."

+ +

In CSS, the ::first-letter pseudo-element applies to +block, list-item, table-cell, table-caption, and inline-block +elements. A future version of this specification +may allow this pesudo-element to apply to more element +types.

+ +

The ::first-letter pseudo-element can be used with all +such elements that contain text, or that have a descendant in the same +flow that contains text. A UA should act as if the fictional start tag +of the ::first-letter pseudo-element is just before the first text of +the element, even if that first text is in a descendant.

+ +
+

Example:

+

The fictional tag sequence for this HTMLfragment: +

<div>
+<p>The first text.
+

is: +

<div>
+<p><div::first-letter><p::first-letter>T</...></...>he first text.
+
+ +

The first letter of a table-cell or inline-block cannot be the +first letter of an ancestor element. Thus, in <DIV><P +STYLE="display: inline-block">Hello<BR>Goodbye</P> +etcetera</DIV> the first letter of the div is not the +letter "H". In fact, the div doesn't have a first letter. + +

The first letter must occur on the first formatted line. For example, in +this fragment: <p><br>First... the first line +doesn't contain any letters and ::first-letter doesn't +match anything (assuming the default style for br in HTML +4). In particular, it does not match the "F" of "First." + +

In CSS, if an element is a list item ('display: list-item'), the +::first-letter applies to the first letter in the +principal box after the marker. UAs may ignore +::first-letter on list items with 'list-style-position: +inside'. If an element has ::before or +::after content, the ::first-letter applies +to the first letter of the element including that content. + +

+

Example:

+

After the rule 'p::before {content: "Note: "}', the selector +'p::first-letter' matches the "N" of "Note".

+
+ +

Some languages may have specific rules about how to treat certain +letter combinations. In Dutch, for example, if the letter combination +"ij" appears at the beginning of a word, both letters should be +considered within the ::first-letter pseudo-element. + +

If the letters that would form the ::first-letter are not in the +same element, such as "'T" in <p>'<em>T..., the UA +may create a ::first-letter pseudo-element from one of the elements, +both elements, or simply not create a pseudo-element.

+ +

Similarly, if the first letter(s) of the block are not at the start +of the line (for example due to bidirectional reordering), then the UA +need not create the pseudo-element(s). + +

+

Example:

+

The following example illustrates +how overlapping pseudo-elements may interact. The first letter of +each P element will be green with a font size of '24pt'. The rest of +the first formatted line will be 'blue' while the rest of the +paragraph will be 'red'.

+ +
p { color: red; font-size: 12pt }
+p::first-letter { color: green; font-size: 200% }
+p::first-line { color: blue }
+
+<P>Some text that ends up on two lines</P>
+ +

Assuming that a line break will occur before the word "ends", the +fictional tag +sequence for this fragment might be:

+ +
<P>
+<P::first-line>
+<P::first-letter> 
+S 
+</P::first-letter>ome text that 
+</P::first-line> 
+ends up on two lines 
+</P>
+ +

Note that the ::first-letter element is inside the ::first-line +element. Properties set on ::first-line are inherited by +::first-letter, but are overridden if the same property is set on +::first-letter.

+
+ + +

7.3. The ::selection pseudo-element

+ +

The ::selection pseudo-element applies to the portion +of a document that has been highlighted by the user. This also +applies, for example, to selected text within an editable text +field. This pseudo-element should not be confused with the :checked pseudo-class (which used to be +named :selected) + +

Although the ::selection pseudo-element is dynamic in +nature, and is altered by user action, it is reasonable to expect that +when a UA re-renders to a static medium (such as a printed page, see +[CSS21]) which was originally rendered to a +dynamic medium (like screen), the UA may wish to transfer the current +::selection state to that other medium, and have all the +appropriate formatting and rendering take effect as well. This is not +required — UAs may omit the ::selection +pseudo-element for static media. + +

These are the CSS properties that apply to ::selection +pseudo-elements: color, background, cursor (optional), outline +(optional). The computed value of the 'background-image' property on +::selection may be ignored. + + +

7.4. The ::before and ::after pseudo-elements

+ +

The ::before and ::after pseudo-elements +can be used to describe generated content before or after an element's +content. They are explained in CSS 2.1 [CSS21].

+ +

When the ::first-letter and ::first-line +pseudo-elements are combined with ::before and +::after, they apply to the first letter or line of the +element including the inserted text.

+ +

8. Combinators

+ +

8.1. Descendant combinator

+ +

At times, authors may want selectors to describe an element that is +the descendant of another element in the document tree (e.g., "an +EM element that is contained within an H1 +element"). Descendant combinators express such a relationship. A +descendant combinator is white space that +separates two sequences of simple selectors. A selector of the form +"A B" represents an element B that is an +arbitrary descendant of some ancestor element A. + +

+

Examples:

+

For example, consider the following selector:

+
h1 em
+

It represents an em element being the descendant of + an h1 element. It is a correct and valid, but partial, + description of the following fragment:

+
<h1>This <span class="myclass">headline
+is <em>very</em> important</span></h1>
+

The following selector:

+
div * p
+

represents a p element that is a grandchild or later + descendant of a div element. Note the whitespace on + either side of the "*" is not part of the universal selector; the + whitespace is a combinator indicating that the DIV must be the + ancestor of some element, and that that element must be an ancestor + of the P.

+

The following selector, which combines descendant combinators and + attribute selectors, represents an + element that (1) has the href attribute set and (2) is + inside a p that is itself inside a div:

+
div p *[href]
+
+ +

8.2. Child combinators

+ +

A child combinator describes a childhood relationship +between two elements. A child combinator is made of the +"greater-than sign" (>) character and +separates two sequences of simple selectors. + + +

+

Examples:

+

The following selector represents a p element that is + child of body:

+
body > p
+

The following example combines descendant combinators and child + combinators.

+
div ol>li p
+

It represents a p element that is a descendant of an + li element; the li element must be the + child of an ol element; the ol element must + be a descendant of a div. Notice that the optional white + space around the ">" combinator has been left out.

+
+ +

For information on selecting the first child of an element, please +see the section on the :first-child pseudo-class +above.

+ +

8.3. Sibling combinators

+ +

There are two different sibling combinators: the adjacent sibling +combinator and the general sibling combinator. In both cases, +non-element nodes (e.g. text between elements) are ignored when +considering adjacency of elements.

+ +

8.3.1. Adjacent sibling combinator

+ +

The adjacent sibling combinator is made of the "plus +sign" (U+002B, +) character that separates two +sequences of simple selectors. The elements represented by the two +sequences share the same parent in the document tree and the element +represented by the first sequence immediately precedes the element +represented by the second one.

+ +
+

Examples:

+

The following selector represents a p element + immediately following a math element:

+
math + p
+

The following selector is conceptually similar to the one in the + previous example, except that it adds an attribute selector — it + adds a constraint to the h1 element, that it must have + class="opener":

+
h1.opener + h2
+
+ + +

8.3.2. General sibling combinator

+ +

The general sibling combinator is made of the "tilde" +(U+007E, ~) character that separates two sequences of +simple selectors. The elements represented by the two sequences share +the same parent in the document tree and the element represented by +the first sequence precedes (not necessarily immediately) the element +represented by the second one.

+ +
+

Example:

+
h1 ~ pre
+

represents a pre element following an h1. It + is a correct and valid, but partial, description of:

+
<h1>Definition of the function a</h1>
+<p>Function a(x) has to be applied to all figures in the table.</p>
+<pre>function a(x) = 12x/13.5</pre>
+
+ +

9. Calculating a selector's specificity

+ +

A selector's specificity is calculated as follows:

+ + + +

Selectors inside the negation pseudo-class +are counted like any other, but the negation itself does not count as +a pseudo-class.

+ +

Concatenating the three numbers a-b-c (in a number system with a +large base) gives the specificity.

+ +
+

Examples:

+
*               /* a=0 b=0 c=0 -> specificity =   0 */
+LI              /* a=0 b=0 c=1 -> specificity =   1 */
+UL LI           /* a=0 b=0 c=2 -> specificity =   2 */
+UL OL+LI        /* a=0 b=0 c=3 -> specificity =   3 */
+H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity =  11 */
+UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */
+LI.red.level    /* a=0 b=2 c=1 -> specificity =  21 */
+#x34y           /* a=1 b=0 c=0 -> specificity = 100 */
+#s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 101 */
+
+
+ +

Note: the specificity of the styles +specified in an HTML style attribute is described in CSS +2.1. [CSS21].

+ +

10. The grammar of Selectors

+ +

10.1. Grammar

+ +

The grammar below defines the syntax of Selectors. It is globally +LL(1) and can be locally LL(2) (but note that most UA's should not use +it directly, since it doesn't express the parsing conventions). The +format of the productions is optimized for human consumption and some +shorthand notations beyond Yacc (see [YACC]) +are used:

+ + + +

The productions are:

+ +
selectors_group
+  : selector [ COMMA S* selector ]*
+  ;
+
+selector
+  : simple_selector_sequence [ combinator simple_selector_sequence ]*
+  ;
+
+combinator
+  /* combinators can be surrounded by white space */
+  : PLUS S* | GREATER S* | TILDE S* | S+
+  ;
+
+simple_selector_sequence
+  : [ type_selector | universal ]
+    [ HASH | class | attrib | pseudo | negation ]*
+  | [ HASH | class | attrib | pseudo | negation ]+
+  ;
+
+type_selector
+  : [ namespace_prefix ]? element_name
+  ;
+
+namespace_prefix
+  : [ IDENT | '*' ]? '|'
+  ;
+
+element_name
+  : IDENT
+  ;
+
+universal
+  : [ namespace_prefix ]? '*'
+  ;
+
+class
+  : '.' IDENT
+  ;
+
+attrib
+  : '[' S* [ namespace_prefix ]? IDENT S*
+        [ [ PREFIXMATCH |
+            SUFFIXMATCH |
+            SUBSTRINGMATCH |
+            '=' |
+            INCLUDES |
+            DASHMATCH ] S* [ IDENT | STRING ] S*
+        ]? ']'
+  ;
+
+pseudo
+  /* '::' starts a pseudo-element, ':' a pseudo-class */
+  /* Exceptions: :first-line, :first-letter, :before and :after. */
+  /* Note that pseudo-elements are restricted to one per selector and */
+  /* occur only in the last simple_selector_sequence. */
+  : ':' ':'? [ IDENT | functional_pseudo ]
+  ;
+
+functional_pseudo
+  : FUNCTION S* expression ')'
+  ;
+
+expression
+  /* In CSS3, the expressions are identifiers, strings, */
+  /* or of the form "an+b" */
+  : [ [ PLUS | '-' | DIMENSION | NUMBER | STRING | IDENT ] S* ]+
+  ;
+
+negation
+  : NOT S* negation_arg S* ')'
+  ;
+
+negation_arg
+  : type_selector | universal | HASH | class | attrib | pseudo
+  ;
+ + +

10.2. Lexical scanner

+ +

The following is the tokenizer, written in Flex (see +[FLEX]) notation. The tokenizer is +case-insensitive.

+ +

The two occurrences of "\377" represent the highest character +number that current versions of Flex can deal with (decimal 255). They +should be read as "\4177777" (decimal 1114111), which is the highest +possible code point in Unicode/ISO-10646. [UNICODE]

+ +
%option case-insensitive
+
+ident     [-]?{nmstart}{nmchar}*
+name      {nmchar}+
+nmstart   [_a-z]|{nonascii}|{escape}
+nonascii  [^\0-\177]
+unicode   \\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?
+escape    {unicode}|\\[^\n\r\f0-9a-f]
+nmchar    [_a-z0-9-]|{nonascii}|{escape}
+num       [0-9]+|[0-9]*\.[0-9]+
+string    {string1}|{string2}
+string1   \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*\"
+string2   \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*\'
+invalid   {invalid1}|{invalid2}
+invalid1  \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*
+invalid2  \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*
+nl        \n|\r\n|\r|\f
+w         [ \t\r\n\f]*
+
+%%
+
+[ \t\r\n\f]+     return S;
+
+"~="             return INCLUDES;
+"|="             return DASHMATCH;
+"^="             return PREFIXMATCH;
+"$="             return SUFFIXMATCH;
+"*="             return SUBSTRINGMATCH;
+{ident}          return IDENT;
+{string}         return STRING;
+{ident}"("       return FUNCTION;
+{num}            return NUMBER;
+"#"{name}        return HASH;
+{w}"+"           return PLUS;
+{w}">"           return GREATER;
+{w}","           return COMMA;
+{w}"~"           return TILDE;
+":not("          return NOT;
+@{ident}         return ATKEYWORD;
+{invalid}        return INVALID;
+{num}%           return PERCENTAGE;
+{num}{ident}     return DIMENSION;
+"<!--"           return CDO;
+"-->"            return CDC;
+
+"url("{w}{string}{w}")"                           return URI;
+"url("{w}([!#$%&*-~]|{nonascii}|{escape})*{w}")"  return URI;
+U\+[0-9a-f?]{1,6}(-[0-9a-f]{1,6})?                return UNICODE_RANGE;
+
+\/\*[^*]*\*+([^/*][^*]*\*+)*\/                    /* ignore comments */
+
+.                return *yytext;
+ + + +

11. Namespaces and down-level clients

+ +

An important issue is the interaction of CSS selectors with XML +documents in web clients that were produced prior to this +document. Unfortunately, due to the fact that namespaces must be +matched based on the URI which identifies the namespace, not the +namespace prefix, some mechanism is required to identify namespaces in +CSS by their URI as well. Without such a mechanism, it is impossible +to construct a CSS style sheet which will properly match selectors in +all cases against a random set of XML documents. However, given +complete knowledge of the XML document to which a style sheet is to be +applied, and a limited use of namespaces within the XML document, it +is possible to construct a style sheet in which selectors would match +elements and attributes correctly.

+ +

It should be noted that a down-level CSS client will (if it +properly conforms to CSS forward compatible parsing rules) ignore all +@namespace at-rules, as well as all style rules that make +use of namespace qualified element type or attribute selectors. The +syntax of delimiting namespace prefixes in CSS was deliberately chosen +so that down-level CSS clients would ignore the style rules rather +than possibly match them incorrectly.

+ +

The use of default namespaces in CSS makes it possible to write +element type selectors that will function in both namespace aware CSS +clients as well as down-level clients. It should be noted that +down-level clients may incorrectly match selectors against XML +elements in other namespaces.

+ +

The following are scenarios and examples in which it is possible to +construct style sheets which would function properly in web clients +that do not implement this proposal.

+ +
    +
  1. + +

    The XML document does not use namespaces.

    + +
      + +
    • In this case, it is obviously not necessary to declare or use + namespaces in the style sheet. Standard CSS element type and + attribute selectors will function adequately in a down-level + client.
    • + +
    • In a CSS namespace aware client, the default behavior of + element selectors matching without regard to namespace will + function properly against all elements, since no namespaces are + present. However, the use of specific element type selectors that + match only elements that have no namespace ("|name") + will guarantee that selectors will match only XML elements that do + not have a declared namespace.
    • + +
    + +
  2. + +
  3. + +

    The XML document defines a single, default namespace used + throughout the document. No namespace prefixes are used in element + names.

    + +
      + +
    • In this case, a down-level client will function as if + namespaces were not used in the XML document at all. Standard CSS + element type and attribute selectors will match against all + elements.
    • + +
    + +
  4. + +
  5. + +

    The XML document does not use a default namespace, all + namespace prefixes used are known to the style sheet author, and + there is a direct mapping between namespace prefixes and namespace + URIs. (A given prefix may only be mapped to one namespace URI + throughout the XML document; there may be multiple prefixes mapped + to the same URI).

    + +
      + +
    • In this case, the down-level client will view and match + element type and attribute selectors based on their fully + qualified name, not the local part as outlined in the Type selectors and Namespaces section. CSS + selectors may be declared using an escaped colon "\:" + to describe the fully qualified names, e.g. + "html\:h1" will match + <html:h1>. Selectors using the qualified name + will only match XML elements that use the same prefix. Other + namespace prefixes used in the XML that are mapped to the same URI + will not match as expected unless additional CSS style rules are + declared for them.
    • + +
    • Note that selectors declared in this fashion will + only match in down-level clients. A CSS namespace aware + client will match element type and attribute selectors based on + the name's local part. Selectors declared with the fully + qualified name will not match (unless there is no namespace prefix + in the fully qualified name).
    • + +
    + +
  6. + +
+ +

In other scenarios: when the namespace prefixes used in the XML are +not known in advance by the style sheet author; or a combination of +elements with no namespace are used in conjunction with elements using +a default namespace; or the same namespace prefix is mapped to +different namespace URIs within the same document, or in +different documents; it is impossible to construct a CSS style sheet +that will function properly against all elements in those documents, +unless, the style sheet is written using a namespace URI syntax (as +outlined in this document or similar) and the document is processed by +a CSS and XML namespace aware client.

+ +

12. Profiles

+ +

Each specification using Selectors must define the subset of W3C +Selectors it allows and excludes, and describe the local meaning of +all the components of that subset.

+ +

Non normative examples: + +

+ + + + + + + + + + + + + + + +
Selectors profile
SpecificationCSS level 1
Acceptstype selectors
class selectors
ID selectors
:link, + :visited and :active pseudo-classes
descendant combinator +
::first-line and ::first-letter pseudo-elements
Excludes + +

universal selector
attribute selectors
:hover and :focus + pseudo-classes
:target pseudo-class
:lang() pseudo-class
all UI + element states pseudo-classes
all structural + pseudo-classes
negation pseudo-class
all + UI element fragments pseudo-elements
::before and ::after + pseudo-elements
child combinators
sibling combinators + +

namespaces

Extra constraintsonly one class selector allowed per sequence of simple + selectors


+ + + + + + + + + + + + + + + +
Selectors profile
SpecificationCSS level 2
Acceptstype selectors
universal selector
attribute presence and + values selectors
class selectors
ID selectors
:link, :visited, + :active, :hover, :focus, :lang() and :first-child pseudo-classes +
descendant combinator
child combinator
adjacent sibling + combinator
::first-line and ::first-letter pseudo-elements
::before + and ::after pseudo-elements
Excludes + +

content selectors
substring matching attribute + selectors
:target pseudo-classes
all UI element + states pseudo-classes
all structural pseudo-classes other + than :first-child
negation pseudo-class
all UI element + fragments pseudo-elements
general sibling combinators + +

namespaces

Extra constraintsmore than one class selector per sequence of simple selectors (CSS1 + constraint) allowed
+ +

In CSS, selectors express pattern matching rules that determine which style +rules apply to elements in the document tree. + +

The following selector (CSS level 2) will match all anchors a +with attribute name set inside a section 1 header h1: +

h1 a[name]
+ +

All CSS declarations attached to such a selector are applied to elements +matching it.

+ +
+ + + + + + + + + + + + + + + + +
Selectors profile
SpecificationSTTS 3
Accepts + +

type selectors
universal selectors
attribute selectors
class + selectors
ID selectors
all structural pseudo-classes
+ all combinators + +

namespaces

Excludesnon-accepted pseudo-classes
pseudo-elements
Extra constraintssome selectors and combinators are not allowed in fragment + descriptions on the right side of STTS declarations.
+ +

Selectors can be used in STTS 3 in two different + manners: +

    +
  1. a selection mechanism equivalent to CSS selection mechanism: declarations + attached to a given selector are applied to elements matching that selector, +
  2. fragment descriptions that appear on the right side of declarations. +
+ +

13. Conformance and requirements

+ +

This section defines conformance with the present specification only. + +

The inability of a user agent to implement part of this specification due to +the limitations of a particular device (e.g., non interactive user agents will +probably not implement dynamic pseudo-classes because they make no sense without +interactivity) does not imply non-conformance. + +

All specifications reusing Selectors must contain a Profile listing the +subset of Selectors it accepts or excludes, and describing the constraints +it adds to the current specification. + +

Invalidity is caused by a parsing error, e.g. an unrecognized token or a token +which is not allowed at the current parsing point. + +

User agents must observe the rules for handling parsing errors: +

+ +

Specifications reusing Selectors must define how to handle parsing +errors. (In the case of CSS, the entire rule in which the selector is +used is dropped.)

+ + + +

14. Tests

+ +

This specification has a test +suite allowing user agents to verify their basic conformance to +the specification. This test suite does not pretend to be exhaustive +and does not cover all possible combined cases of Selectors.

+ +

15. Acknowledgements

+ +

The CSS working group would like to thank everyone who has sent +comments on this specification over the years.

+ +

The working group would like to extend special thanks to Donna +McManus, Justin Baker, Joel Sklar, and Molly Ives Brower who perfermed +the final editorial review.

+ +

16. References

+ +
+ +
[CSS1] +
Bert Bos, Håkon Wium Lie; "Cascading Style Sheets, level 1", W3C Recommendation, 17 Dec 1996, revised 11 Jan 1999 +
(http://www.w3.org/TR/REC-CSS1) + +
[CSS21] +
Bert Bos, Tantek Çelik, Ian Hickson, Håkon Wium Lie, editors; "Cascading Style Sheets, level 2 revision 1", W3C Working Draft, 13 June 2005 +
(http://www.w3.org/TR/CSS21) + +
[CWWW] +
Martin J. Dürst, François Yergeau, Misha Wolf, Asmus Freytag, Tex Texin, editors; "Character Model for the World Wide Web", W3C Recommendation, 15 February 2005 +
(http://www.w3.org/TR/charmod/) + +
[FLEX] +
"Flex: The Lexical Scanner Generator", Version 2.3.7, ISBN 1882114213 + +
[HTML4] +
Dave Ragget, Arnaud Le Hors, Ian Jacobs, editors; "HTML 4.01 Specification", W3C Recommendation, 24 December 1999 +
(http://www.w3.org/TR/html4/) + +
[MATH] +
Patrick Ion, Robert Miner, editors; "Mathematical Markup Language (MathML) 1.01", W3C Recommendation, revision of 7 July 1999 +
(http://www.w3.org/TR/REC-MathML/) + +
[RFC3066] +
H. Alvestrand; "Tags for the Identification of Languages", Request for Comments 3066, January 2001 +
(http://www.ietf.org/rfc/rfc3066.txt) + +
[STTS] +
Daniel Glazman; "Simple Tree Transformation Sheets 3", Electricité de France, submission to the W3C, 11 November 1998 +
(http://www.w3.org/TR/NOTE-STTS3) + +
[SVG] +
Jon Ferraiolo, 藤沢 淳, Dean Jackson, editors; "Scalable Vector Graphics (SVG) 1.1 Specification", W3C Recommendation, 14 January 2003 +
(http://www.w3.org/TR/SVG/) + +
[UNICODE]
+
The Unicode Standard, Version 4.1, The Unicode Consortium. Boston, MA, Addison-Wesley, March 2005. ISBN 0-321-18578-1, as amended by Unicode 4.0.1 and Unicode 4.1.0. +
(http://www.unicode.org/versions/)
+ +
[XML10] +
Tim Bray, Jean Paoli, C. M. Sperberg-McQueen, Eve Maler, François Yergeau, editors; "Extensible Markup Language (XML) 1.0 (Third Edition)", W3C Recommendation, 4 February 2004 +
(http://www.w3.org/TR/REC-xml/) + +
[XMLNAMES] +
Tim Bray, Dave Hollander, Andrew Layman, editors; "Namespaces in XML", W3C Recommendation, 14 January 1999 +
(http://www.w3.org/TR/REC-xml-names/) + +
[YACC] +
S. C. Johnson; "YACC — Yet another compiler compiler", Technical Report, Murray Hill, 1975 + +
+ +
+ test +
+
+
+ test +
+ test +
+
+
+ test +
+
+
+
+ +
+ d1d1 + d2d2 + d3d3 + d4d4 + d5d5 + d6d6 + + + + + + +
+
+ d1 + d1 + + d2 + d2 + + d3 + d3 + + d4 + d4 + + d5 + d5 + + d6 + d6 + +
+ + + diff --git a/test_new/browser/fixtures/slick/template-standard.html b/test_new/browser/fixtures/slick/template-standard.html new file mode 100644 index 0000000..156f33a --- /dev/null +++ b/test_new/browser/fixtures/slick/template-standard.html @@ -0,0 +1,2932 @@ + + + + + + + + + template xhtml as html + + + +
+

W3C + +

Selectors

+ +

W3C Working Draft 15 December 2005

+ +
+ +
This version: + +
+ http://www.w3.org/TR/2005/WD-css3-selectors-20051215 + +
Latest version: + +
+ http://www.w3.org/TR/css3-selectors + +
Previous version: + +
+ http://www.w3.org/TR/2001/CR-css3-selectors-20011113 + +
Editors: + +
Daniel Glazman (Invited Expert)
+ +
Tantek Çelik (Invited Expert) + +
Ian Hickson (Google) + +
Peter Linss (former editor, Netscape/AOL) + +
John Williams (former editor, Quark, Inc.) + +
+ +
+ +
+ +

Abstract

+ +

Selectors are patterns that match against elements in a + tree. Selectors have been optimized for use with HTML and XML, and + are designed to be usable in performance-critical code.

+ +

CSS (Cascading + Style Sheets) is a language for describing the rendering of HTML and XML documents on + screen, on paper, in speech, etc. CSS uses Selectors for binding + style properties to elements in the document. This document + describes extensions to the selectors defined in CSS level 2. These + extended selectors will be used by CSS level 3. + +

Selectors define the following function:

+ +
expression ∗ element → boolean
+ +

That is, given an element and a selector, this specification + defines whether that element matches the selector.

+ +

These expressions can also be used, for instance, to select a set + of elements, or a single element from a set of elements, by + evaluating the expression across all the elements in a + subtree. STTS (Simple Tree Transformation Sheets), a + language for transforming XML trees, uses this mechanism. [STTS]

+ +

Status of this document

+ +

This section describes the status of this document at the + time of its publication. Other documents may supersede this + document. A list of current W3C publications and the latest revision + of this technical report can be found in the W3C technical reports index at + http://www.w3.org/TR/.

+ +

This document describes the selectors that already exist in CSS1 and CSS2, and + also proposes new selectors for CSS3 and other languages that may need them.

+ +

The CSS Working Group doesn't expect that all implementations of + CSS3 will have to implement all selectors. Instead, there will + probably be a small number of variants of CSS3, called profiles. For + example, it may be that only a profile for interactive user agents + will include all of the selectors.

+ +

This specification is a last call working draft for the the CSS Working Group + (Style Activity). This + document is a revision of the Candidate + Recommendation dated 2001 November 13, and has incorporated + implementation feedback received in the past few years. It is + expected that this last call will proceed straight to Proposed + Recommendation stage since it is believed that interoperability will + be demonstrable.

+ +

All persons are encouraged to review and implement this + specification and return comments to the (archived) + public mailing list www-style + (see instructions). W3C + Members can also send comments directly to the CSS Working + Group. + The deadline for comments is 14 January 2006.

+ +

This is still a draft document and may be updated, replaced, or + obsoleted by other documents at any time. It is inappropriate to + cite a W3C Working Draft as other than "work in progress". + +

This document may be available in translation. + The English version of this specification is the only normative + version. + +

+ +

Table of contents

+ + + +
+ +

1. Introduction

+ +

1.1. Dependencies

+ +

Some features of this specification are specific to CSS, or have + particular limitations or rules specific to CSS. In this + specification, these have been described in terms of CSS2.1. [CSS21]

+ +

1.2. Terminology

+ +

All of the text of this specification is normative except + examples, notes, and sections explicitly marked as + non-normative.

+ +

1.3. Changes from CSS2

+ +

This section is non-normative.

+ +

The main differences between the selectors in CSS2 and those in + Selectors are: + +

+ +

2. Selectors

+ +

This section is non-normative, as it merely summarizes the +following sections.

+ +

A Selector represents a structure. This structure can be used as a +condition (e.g. in a CSS rule) that determines which elements a +selector matches in the document tree, or as a flat description of the +HTML or XML fragment corresponding to that structure.

+ +

Selectors may range from simple element names to rich contextual +representations.

+ +

The following table summarizes the Selector syntax:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PatternMeaningDescribed in sectionFirst defined in CSS level
*any elementUniversal + selector2
Ean element of type EType selector1
E[foo]an E element with a "foo" attributeAttribute + selectors2
E[foo="bar"]an E element whose "foo" attribute value is exactly + equal to "bar"Attribute + selectors2
E[foo~="bar"]an E element whose "foo" attribute value is a list of + space-separated values, one of which is exactly equal to "bar"Attribute + selectors2
E[foo^="bar"]an E element whose "foo" attribute value begins exactly + with the string "bar"Attribute + selectors3
E[foo$="bar"]an E element whose "foo" attribute value ends exactly + with the string "bar"Attribute + selectors3
E[foo*="bar"]an E element whose "foo" attribute value contains the + substring "bar"Attribute + selectors3
E[hreflang|="en"]an E element whose "hreflang" attribute has a hyphen-separated + list of values beginning (from the left) with "en"Attribute + selectors2
E:rootan E element, root of the documentStructural + pseudo-classes3
E:nth-child(n)an E element, the n-th child of its parentStructural + pseudo-classes3
E:nth-last-child(n)an E element, the n-th child of its parent, counting + from the last oneStructural + pseudo-classes3
E:nth-of-type(n)an E element, the n-th sibling of its typeStructural + pseudo-classes3
E:nth-last-of-type(n)an E element, the n-th sibling of its type, counting + from the last oneStructural + pseudo-classes3
E:first-childan E element, first child of its parentStructural + pseudo-classes2
E:last-childan E element, last child of its parentStructural + pseudo-classes3
E:first-of-typean E element, first sibling of its typeStructural + pseudo-classes3
E:last-of-typean E element, last sibling of its typeStructural + pseudo-classes3
E:only-childan E element, only child of its parentStructural + pseudo-classes3
E:only-of-typean E element, only sibling of its typeStructural + pseudo-classes3
E:emptyan E element that has no children (including text + nodes)Structural + pseudo-classes3
E:link
E:visited
an E element being the source anchor of a hyperlink of + which the target is not yet visited (:link) or already visited + (:visited)The link + pseudo-classes1
E:active
E:hover
E:focus
an E element during certain user actionsThe user + action pseudo-classes1 and 2
E:targetan E element being the target of the referring URIThe target + pseudo-class3
E:lang(fr)an element of type E in language "fr" (the document + language specifies how language is determined)The :lang() + pseudo-class2
E:enabled
E:disabled
a user interface element E which is enabled or + disabledThe UI element states + pseudo-classes3
E:checkeda user interface element E which is checked (for instance a radio-button or checkbox)The UI element states + pseudo-classes3
E::first-linethe first formatted line of an E elementThe ::first-line + pseudo-element1
E::first-letterthe first formatted letter of an E elementThe ::first-letter + pseudo-element1
E::selectionthe portion of an E element that is currently + selected/highlighted by the userThe UI element + fragments pseudo-elements3
E::beforegenerated content before an E elementThe ::before + pseudo-element2
E::aftergenerated content after an E elementThe ::after + pseudo-element2
E.warningan E element whose class is +"warning" (the document language specifies how class is determined).Class + selectors1
E#myidan E element with ID equal to "myid".ID + selectors1
E:not(s)an E element that does not match simple selector sNegation + pseudo-class3
E Fan F element descendant of an E elementDescendant + combinator1
E > Fan F element child of an E elementChild + combinator2
E + Fan F element immediately preceded by an E elementAdjacent sibling combinator2
E ~ Fan F element preceded by an E elementGeneral sibling combinator3
+ +

The meaning of each selector is derived from the table above by +prepending "matches" to the contents of each cell in the "Meaning" +column.

+ +

3. Case sensitivity

+ +

The case sensitivity of document language element names, attribute +names, and attribute values in selectors depends on the document +language. For example, in HTML, element names are case-insensitive, +but in XML, they are case-sensitive.

+ +

4. Selector syntax

+ +

A selector is a chain of one +or more sequences of simple selectors +separated by combinators.

+ +

A sequence of simple selectors +is a chain of simple selectors +that are not separated by a combinator. It +always begins with a type selector or a +universal selector. No other type +selector or universal selector is allowed in the sequence.

+ +

A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, content selector, or pseudo-class. One pseudo-element may be appended to the last +sequence of simple selectors.

+ +

Combinators are: white space, "greater-than +sign" (U+003E, >), "plus sign" (U+002B, ++) and "tilde" (U+007E, ~). White +space may appear between a combinator and the simple selectors around +it. Only the characters "space" (U+0020), "tab" +(U+0009), "line feed" (U+000A), "carriage return" (U+000D), and "form +feed" (U+000C) can occur in white space. Other space-like characters, +such as "em-space" (U+2003) and "ideographic space" (U+3000), are +never part of white space.

+ +

The elements of a document tree that are represented by a selector +are the subjects of the selector. A +selector consisting of a single sequence of simple selectors +represents any element satisfying its requirements. Prepending another +sequence of simple selectors and a combinator to a sequence imposes +additional matching constraints, so the subjects of a selector are +always a subset of the elements represented by the last sequence of +simple selectors.

+ +

An empty selector, containing no sequence of simple selectors and +no pseudo-element, is an invalid +selector.

+ +

5. Groups of selectors

+ +

When several selectors share the same declarations, they may be +grouped into a comma-separated list. (A comma is U+002C.)

+ +
+

CSS examples:

+

In this example, we condense three rules with identical +declarations into one. Thus,

+
h1 { font-family: sans-serif }
+h2 { font-family: sans-serif }
+h3 { font-family: sans-serif }
+

is equivalent to:

+
h1, h2, h3 { font-family: sans-serif }
+
+ +

Warning: the equivalence is true in this example +because all the selectors are valid selectors. If just one of these +selectors were invalid, the entire group of selectors would be +invalid. This would invalidate the rule for all three heading +elements, whereas in the former case only one of the three individual +heading rules would be invalidated.

+ + +

6. Simple selectors

+ +

6.1. Type selector

+ +

A type selector is the name of a document language +element type. A type selector represents an instance of the element +type in the document tree.

+ +
+

Example:

+

The following selector represents an h1 element in the document tree:

+
h1
+
+ + +

6.1.1. Type selectors and namespaces

+ +

Type selectors allow an optional namespace ([XMLNAMES]) component. A namespace prefix +that has been previously declared may be prepended to the element name +separated by the namespace separator "vertical bar" +(U+007C, |).

+ +

The namespace component may be left empty to indicate that the +selector is only to represent elements with no declared namespace.

+ +

An asterisk may be used for the namespace prefix, indicating that +the selector represents elements in any namespace (including elements +with no namespace).

+ +

Element type selectors that have no namespace component (no +namespace separator), represent elements without regard to the +element's namespace (equivalent to "*|") unless a default +namespace has been declared. If a default namespace has been declared, +the selector will represent only elements in the default +namespace.

+ +

A type selector containing a namespace prefix that has not been +previously declared is an invalid selector. +The mechanism for declaring a namespace prefix is left up to the +language implementing Selectors. In CSS, such a mechanism is defined +in the General Syntax module.

+ +

In a namespace-aware client, element type selectors will only match +against the local part +of the element's qualified +name. See below for notes about matching +behaviors in down-level clients.

+ +

In summary:

+ +
+
ns|E
+
elements with name E in namespace ns
+
*|E
+
elements with name E in any namespace, including those without any + declared namespace
+
|E
+
elements with name E without any declared namespace
+
E
+
if no default namespace has been specified, this is equivalent to *|E. + Otherwise it is equivalent to ns|E where ns is the default namespace.
+
+ +
+

CSS examples:

+ +
@namespace foo url(http://www.example.com);
+ foo|h1 { color: blue }
+ foo|* { color: yellow }
+ |h1 { color: red }
+ *|h1 { color: green }
+ h1 { color: green }
+ +

The first rule will match only h1 elements in the + "http://www.example.com" namespace.

+ +

The second rule will match all elements in the + "http://www.example.com" namespace.

+ +

The third rule will match only h1 elements without + any declared namespace.

+ +

The fourth rule will match h1 elements in any + namespace (including those without any declared namespace).

+ +

The last rule is equivalent to the fourth rule because no default + namespace has been defined.

+ +
+ +

6.2. Universal selector

+ +

The universal selector, written "asterisk" +(*), represents the qualified name of any element +type. It represents any single element in the document tree in any +namespace (including those without any declared namespace) if no +default namespace has been specified. If a default namespace has been +specified, see Universal selector and +Namespaces below.

+ +

If the universal selector is not the only component of a sequence +of simple selectors, the * may be omitted.

+ +
+

Examples:

+
    +
  • *[hreflang|=en] and [hreflang|=en] are equivalent,
  • +
  • *.warning and .warning are equivalent,
  • +
  • *#myid and #myid are equivalent.
  • +
+
+ +

Note: it is recommended that the +*, representing the universal selector, not be +omitted.

+ +

6.2.1. Universal selector and namespaces

+ +

The universal selector allows an optional namespace component. It +is used as follows:

+ +
+
ns|*
+
all elements in namespace ns
+
*|*
+
all elements
+
|*
+
all elements without any declared namespace
+
*
+
if no default namespace has been specified, this is equivalent to *|*. + Otherwise it is equivalent to ns|* where ns is the default namespace.
+
+ +

A universal selector containing a namespace prefix that has not +been previously declared is an invalid +selector. The mechanism for declaring a namespace prefix is left up +to the language implementing Selectors. In CSS, such a mechanism is +defined in the General Syntax module.

+ + +

6.3. Attribute selectors

+ +

Selectors allow the representation of an element's attributes. When +a selector is used as an expression to match against an element, +attribute selectors must be considered to match an element if that +element has an attribute that matches the attribute represented by the +attribute selector.

+ +

6.3.1. Attribute presence and values +selectors

+ +

CSS2 introduced four attribute selectors:

+ +
+
[att] +
Represents an element with the att attribute, whatever the value of + the attribute.
+
[att=val]
+
Represents an element with the att attribute whose value is exactly + "val".
+
[att~=val]
+
Represents an element with the att attribute whose value is a whitespace-separated list of words, one of + which is exactly "val". If "val" contains whitespace, it will never + represent anything (since the words are separated by + spaces).
+
[att|=val] +
Represents an element with the att attribute, its value either + being exactly "val" or beginning with "val" immediately followed by + "-" (U+002D). This is primarily intended to allow language subcode + matches (e.g., the hreflang attribute on the + link element in HTML) as described in RFC 3066 ([RFC3066]). For lang (or + xml:lang) language subcode matching, please see the :lang pseudo-class.
+
+ +

Attribute values must be identifiers or strings. The +case-sensitivity of attribute names and values in selectors depends on +the document language.

+ +
+ +

Examples:

+ +

The following attribute selector represents an h1 + element that carries the title attribute, whatever its + value:

+ +
h1[title]
+ +

In the following example, the selector represents a + span element whose class attribute has + exactly the value "example":

+ +
span[class="example"]
+ +

Multiple attribute selectors can be used to represent several + attributes of an element, or several conditions on the same + attribute. Here, the selector represents a span element + whose hello attribute has exactly the value "Cleveland" + and whose goodbye attribute has exactly the value + "Columbus":

+ +
span[hello="Cleveland"][goodbye="Columbus"]
+ +

The following selectors illustrate the differences between "=" + and "~=". The first selector will represent, for example, the value + "copyright copyleft copyeditor" on a rel attribute. The + second selector will only represent an a element with + an href attribute having the exact value + "http://www.w3.org/".

+ +
a[rel~="copyright"]
+a[href="http://www.w3.org/"]
+ +

The following selector represents a link element + whose hreflang attribute is exactly "fr".

+ +
link[hreflang=fr]
+ +

The following selector represents a link element for + which the values of the hreflang attribute begins with + "en", including "en", "en-US", and "en-cockney":

+ +
link[hreflang|="en"]
+ +

Similarly, the following selectors represents a + DIALOGUE element whenever it has one of two different + values for an attribute character:

+ +
DIALOGUE[character=romeo]
+DIALOGUE[character=juliet]
+ +
+ +

6.3.2. Substring matching attribute +selectors

+ +

Three additional attribute selectors are provided for matching +substrings in the value of an attribute:

+ +
+
[att^=val]
+
Represents an element with the att attribute whose value begins + with the prefix "val".
+
[att$=val] +
Represents an element with the att attribute whose value ends with + the suffix "val".
+
[att*=val] +
Represents an element with the att attribute whose value contains + at least one instance of the substring "val".
+
+ +

Attribute values must be identifiers or strings. The +case-sensitivity of attribute names in selectors depends on the +document language.

+ +
+

Examples:

+

The following selector represents an HTML object, referencing an + image:

+
object[type^="image/"]
+

The following selector represents an HTML anchor a with an + href attribute whose value ends with ".html".

+
a[href$=".html"]
+

The following selector represents an HTML paragraph with a title + attribute whose value contains the substring "hello"

+
p[title*="hello"]
+
+ +

6.3.3. Attribute selectors and namespaces

+ +

Attribute selectors allow an optional namespace component to the +attribute name. A namespace prefix that has been previously declared +may be prepended to the attribute name separated by the namespace +separator "vertical bar" (|). In keeping with +the Namespaces in the XML recommendation, default namespaces do not +apply to attributes, therefore attribute selectors without a namespace +component apply only to attributes that have no declared namespace +(equivalent to "|attr"). An asterisk may be used for the +namespace prefix indicating that the selector is to match all +attribute names without regard to the attribute's namespace. + +

An attribute selector with an attribute name containing a namespace +prefix that has not been previously declared is an invalid selector. The mechanism for declaring +a namespace prefix is left up to the language implementing Selectors. +In CSS, such a mechanism is defined in the General Syntax module. + +

+

CSS examples:

+
@namespace foo "http://www.example.com";
+[foo|att=val] { color: blue }
+[*|att] { color: yellow }
+[|att] { color: green }
+[att] { color: green }
+ +

The first rule will match only elements with the attribute + att in the "http://www.example.com" namespace with the + value "val".

+ +

The second rule will match only elements with the attribute + att regardless of the namespace of the attribute + (including no declared namespace).

+ +

The last two rules are equivalent and will match only elements + with the attribute att where the attribute is not + declared to be in a namespace.

+ +
+ +

6.3.4. Default attribute values in DTDs

+ +

Attribute selectors represent explicitly set attribute values in +the document tree. Default attribute values may be defined in a DTD or +elsewhere, but cannot always be selected by attribute +selectors. Selectors should be designed so that they work even if the +default values are not included in the document tree.

+ +

More precisely, a UA is not required to read an "external +subset" of the DTD but is required to look for default +attribute values in the document's "internal subset." (See [XML10] for definitions of these subsets.)

+ +

A UA that recognizes an XML namespace [XMLNAMES] is not required to use its +knowledge of that namespace to treat default attribute values as if +they were present in the document. (For example, an XHTML UA is not +required to use its built-in knowledge of the XHTML DTD.)

+ +

Note: Typically, implementations +choose to ignore external subsets.

+ +
+

Example:

+ +

Consider an element EXAMPLE with an attribute "notation" that has a +default value of "decimal". The DTD fragment might be

+ +
<!ATTLIST EXAMPLE notation (decimal,octal) "decimal">
+ +

If the style sheet contains the rules

+ +
EXAMPLE[notation=decimal] { /*... default property settings ...*/ }
+EXAMPLE[notation=octal]   { /*... other settings...*/ }
+ +

the first rule will not match elements whose "notation" attribute +is set by default, i.e. not set explicitly. To catch all cases, the +attribute selector for the default value must be dropped:

+ +
EXAMPLE                   { /*... default property settings ...*/ }
+EXAMPLE[notation=octal]   { /*... other settings...*/ }
+ +

Here, because the selector EXAMPLE[notation=octal] is +more specific than the tag +selector alone, the style declarations in the second rule will override +those in the first for elements that have a "notation" attribute value +of "octal". Care has to be taken that all property declarations that +are to apply only to the default case are overridden in the non-default +cases' style rules.

+ +
+ +

6.4. Class selectors

+ +

Working with HTML, authors may use the period (U+002E, +.) notation as an alternative to the ~= +notation when representing the class attribute. Thus, for +HTML, div.value and div[class~=value] have +the same meaning. The attribute value must immediately follow the +"period" (.).

+ +

UAs may apply selectors using the period (.) notation in XML +documents if the UA has namespace-specific knowledge that allows it to +determine which attribute is the "class" attribute for the +respective namespace. One such example of namespace-specific knowledge +is the prose in the specification for a particular namespace (e.g. SVG +1.0 [SVG] describes the SVG +"class" attribute and how a UA should interpret it, and +similarly MathML 1.01 [MATH] describes the MathML +"class" attribute.)

+ +
+

CSS examples:

+ +

We can assign style information to all elements with + class~="pastoral" as follows:

+ +
*.pastoral { color: green }  /* all elements with class~=pastoral */
+ +

or just

+ +
.pastoral { color: green }  /* all elements with class~=pastoral */
+ +

The following assigns style only to H1 elements with + class~="pastoral":

+ +
H1.pastoral { color: green }  /* H1 elements with class~=pastoral */
+ +

Given these rules, the first H1 instance below would not have + green text, while the second would:

+ +
<H1>Not green</H1>
+<H1 class="pastoral">Very green</H1>
+ +
+ +

To represent a subset of "class" values, each value must be preceded +by a ".", in any order.

+ +
+ +

CSS example:

+ +

The following rule matches any P element whose "class" attribute + has been assigned a list of whitespace-separated values that includes + "pastoral" and "marine":

+ +
p.pastoral.marine { color: green }
+ +

This rule matches when class="pastoral blue aqua + marine" but does not match for class="pastoral + blue".

+ +
+ +

Note: Because CSS gives considerable +power to the "class" attribute, authors could conceivably design their +own "document language" based on elements with almost no associated +presentation (such as DIV and SPAN in HTML) and assigning style +information through the "class" attribute. Authors should avoid this +practice since the structural elements of a document language often +have recognized and accepted meanings and author-defined classes may +not.

+ +

Note: If an element has multiple +class attributes, their values must be concatenated with spaces +between the values before searching for the class. As of this time the +working group is not aware of any manner in which this situation can +be reached, however, so this behavior is explicitly non-normative in +this specification.

+ +

6.5. ID selectors

+ +

Document languages may contain attributes that are declared to be +of type ID. What makes attributes of type ID special is that no two +such attributes can have the same value in a document, regardless of +the type of the elements that carry them; whatever the document +language, an ID typed attribute can be used to uniquely identify its +element. In HTML all ID attributes are named "id"; XML applications +may name ID attributes differently, but the same restriction +applies.

+ +

An ID-typed attribute of a document language allows authors to +assign an identifier to one element instance in the document tree. W3C +ID selectors represent an element instance based on its identifier. An +ID selector contains a "number sign" (U+0023, +#) immediately followed by the ID value, which must be an +identifier.

+ +

Selectors does not specify how a UA knows the ID-typed attribute of +an element. The UA may, e.g., read a document's DTD, have the +information hard-coded or ask the user. + +

+

Examples:

+

The following ID selector represents an h1 element + whose ID-typed attribute has the value "chapter1":

+
h1#chapter1
+

The following ID selector represents any element whose ID-typed + attribute has the value "chapter1":

+
#chapter1
+

The following selector represents any element whose ID-typed + attribute has the value "z98y".

+
*#z98y
+
+ +

Note. In XML 1.0 [XML10], the information about which attribute +contains an element's IDs is contained in a DTD or a schema. When +parsing XML, UAs do not always read the DTD, and thus may not know +what the ID of an element is (though a UA may have namespace-specific +knowledge that allows it to determine which attribute is the ID +attribute for that namespace). If a style sheet designer knows or +suspects that a UA may not know what the ID of an element is, he +should use normal attribute selectors instead: +[name=p371] instead of #p371. Elements in +XML 1.0 documents without a DTD do not have IDs at all.

+ +

If an element has multiple ID attributes, all of them must be +treated as IDs for that element for the purposes of the ID +selector. Such a situation could be reached using mixtures of xml:id, +DOM3 Core, XML DTDs, and namespace-specific knowledge.

+ +

6.6. Pseudo-classes

+ +

The pseudo-class concept is introduced to permit selection based on +information that lies outside of the document tree or that cannot be +expressed using the other simple selectors.

+ +

A pseudo-class always consists of a "colon" +(:) followed by the name of the pseudo-class and +optionally by a value between parentheses.

+ +

Pseudo-classes are allowed in all sequences of simple selectors +contained in a selector. Pseudo-classes are allowed anywhere in +sequences of simple selectors, after the leading type selector or +universal selector (possibly omitted). Pseudo-class names are +case-insensitive. Some pseudo-classes are mutually exclusive, while +others can be applied simultaneously to the same +element. Pseudo-classes may be dynamic, in the sense that an element +may acquire or lose a pseudo-class while a user interacts with the +document.

+ + +

6.6.1. Dynamic pseudo-classes

+ +

Dynamic pseudo-classes classify elements on characteristics other +than their name, attributes, or content, in principle characteristics +that cannot be deduced from the document tree.

+ +

Dynamic pseudo-classes do not appear in the document source or +document tree.

+ + +
The link pseudo-classes: :link and :visited
+ +

User agents commonly display unvisited links differently from +previously visited ones. Selectors +provides the pseudo-classes :link and +:visited to distinguish them:

+ + + +

After some amount of time, user agents may choose to return a +visited link to the (unvisited) ':link' state.

+ +

The two states are mutually exclusive.

+ +
+ +

Example:

+ +

The following selector represents links carrying class + external and already visited:

+ +
a.external:visited
+ +
+ +

Note: It is possible for style sheet +authors to abuse the :link and :visited pseudo-classes to determine +which sites a user has visited without the user's consent. + +

UAs may therefore treat all links as unvisited links, or implement +other measures to preserve the user's privacy while rendering visited +and unvisited links differently.

+ +
The user action pseudo-classes +:hover, :active, and :focus
+ +

Interactive user agents sometimes change the rendering in response +to user actions. Selectors provides +three pseudo-classes for the selection of an element the user is +acting on.

+ + + +

There may be document language or implementation specific limits on +which elements can become :active or acquire +:focus.

+ +

These pseudo-classes are not mutually exclusive. An element may +match several pseudo-classes at the same time.

+ +

Selectors doesn't define if the parent of an element that is +':active' or ':hover' is also in that state.

+ +
+

Examples:

+
a:link    /* unvisited links */
+a:visited /* visited links */
+a:hover   /* user hovers */
+a:active  /* active links */
+

An example of combining dynamic pseudo-classes:

+
a:focus
+a:focus:hover
+

The last selector matches a elements that are in + the pseudo-class :focus and in the pseudo-class :hover.

+
+ +

Note: An element can be both ':visited' +and ':active' (or ':link' and ':active').

+ +

6.6.2. The target pseudo-class :target

+ +

Some URIs refer to a location within a resource. This kind of URI +ends with a "number sign" (#) followed by an anchor +identifier (called the fragment identifier).

+ +

URIs with fragment identifiers link to a certain element within the +document, known as the target element. For instance, here is a URI +pointing to an anchor named section_2 in an HTML +document:

+ +
http://example.com/html/top.html#section_2
+ +

A target element can be represented by the :target +pseudo-class. If the document's URI has no fragment identifier, then +the document has no target element.

+ +
+

Example:

+
p.note:target
+

This selector represents a p element of class + note that is the target element of the referring + URI.

+
+ +
+

CSS example:

+

Here, the :target pseudo-class is used to make the + target element red and place an image before it, if there is one:

+
*:target { color : red }
+*:target::before { content : url(target.png) }
+
+ +

6.6.3. The language pseudo-class :lang

+ +

If the document language specifies how the human language of an +element is determined, it is possible to write selectors that +represent an element based on its language. For example, in HTML [HTML4], the language is determined by a +combination of the lang attribute, the meta +element, and possibly by information from the protocol (such as HTTP +headers). XML uses an attribute called xml:lang, and +there may be other document language-specific methods for determining +the language.

+ +

The pseudo-class :lang(C) represents an element that +is in language C. Whether an element is represented by a +:lang() selector is based solely on the identifier C +being either equal to, or a hyphen-separated substring of, the +element's language value, in the same way as if performed by the '|=' operator in attribute +selectors. The identifier C does not have to be a valid language +name.

+ +

C must not be empty. (If it is, the selector is invalid.)

+ +

Note: It is recommended that +documents and protocols indicate language using codes from RFC 3066 [RFC3066] or its successor, and by means of +"xml:lang" attributes in the case of XML-based documents [XML10]. See +"FAQ: Two-letter or three-letter language codes."

+ +
+

Examples:

+

The two following selectors represent an HTML document that is in + Belgian, French, or German. The two next selectors represent + q quotations in an arbitrary element in Belgian, French, + or German.

+
html:lang(fr-be)
+html:lang(de)
+:lang(fr-be) > q
+:lang(de) > q
+
+ +

6.6.4. The UI element states pseudo-classes

+ +
The :enabled and :disabled pseudo-classes
+ +

The :enabled pseudo-class allows authors to customize +the look of user interface elements that are enabled — which the +user can select or activate in some fashion (e.g. clicking on a button +with a mouse). There is a need for such a pseudo-class because there +is no way to programmatically specify the default appearance of say, +an enabled input element without also specifying what it +would look like when it was disabled.

+ +

Similar to :enabled, :disabled allows the +author to specify precisely how a disabled or inactive user interface +element should look.

+ +

Most elements will be neither enabled nor disabled. An element is +enabled if the user can either activate it or transfer the focus to +it. An element is disabled if it could be enabled, but the user cannot +presently activate it or transfer focus to it.

+ + +
The :checked pseudo-class
+ +

Radio and checkbox elements can be toggled by the user. Some menu +items are "checked" when the user selects them. When such elements are +toggled "on" the :checked pseudo-class applies. The +:checked pseudo-class initially applies to such elements +that have the HTML4 selected and checked +attributes as described in Section +17.2.1 of HTML4, but of course the user can toggle "off" such +elements in which case the :checked pseudo-class would no +longer apply. While the :checked pseudo-class is dynamic +in nature, and is altered by user action, since it can also be based +on the presence of the semantic HTML4 selected and +checked attributes, it applies to all media. + + +

The :indeterminate pseudo-class
+ +
+ +

Radio and checkbox elements can be toggled by the user, but are +sometimes in an indeterminate state, neither checked nor unchecked. +This can be due to an element attribute, or DOM manipulation.

+ +

A future version of this specification may introduce an +:indeterminate pseudo-class that applies to such elements. +

+ +
+ + +

6.6.5. Structural pseudo-classes

+ +

Selectors introduces the concept of structural +pseudo-classes to permit selection based on extra information that lies in +the document tree but cannot be represented by other simple selectors or +combinators. + +

Note that standalone pieces of PCDATA (text nodes in the DOM) are +not counted when calculating the position of an element in the list of +children of its parent. When calculating the position of an element in +the list of children of its parent, the index numbering starts at 1. + + +

:root pseudo-class
+ +

The :root pseudo-class represents an element that is +the root of the document. In HTML 4, this is always the +HTML element. + + +

:nth-child() pseudo-class
+ +

The +:nth-child(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings +before it in the document tree, for a given positive +integer or zero value of n, and has a parent element. In +other words, this matches the bth child of an element after +all the children have been split into groups of a elements +each. For example, this allows the selectors to address every other +row in a table, and could be used to alternate the color +of paragraph text in a cycle of four. The a and +b values must be zero, negative integers or positive +integers. The index of the first child of an element is 1. + +

In addition to this, :nth-child() can take +'odd' and 'even' as arguments instead. +'odd' has the same signification as 2n+1, +and 'even' has the same signification as 2n. + + +

+

Examples:

+
tr:nth-child(2n+1) /* represents every odd row of an HTML table */
+tr:nth-child(odd)  /* same */
+tr:nth-child(2n)   /* represents every even row of an HTML table */
+tr:nth-child(even) /* same */
+
+/* Alternate paragraph colours in CSS */
+p:nth-child(4n+1) { color: navy; }
+p:nth-child(4n+2) { color: green; }
+p:nth-child(4n+3) { color: maroon; }
+p:nth-child(4n+4) { color: purple; }
+
+ +

When a=0, no repeating is used, so for example +:nth-child(0n+5) matches only the fifth child. When +a=0, the an part need not be +included, so the syntax simplifies to +:nth-child(b) and the last example simplifies +to :nth-child(5). + +

+

Examples:

+
foo:nth-child(0n+1)   /* represents an element foo, first child of its parent element */
+foo:nth-child(1)      /* same */
+
+ +

When a=1, the number may be omitted from the rule. + +

+

Examples:

+

The following selectors are therefore equivalent:

+
bar:nth-child(1n+0)   /* represents all bar elements, specificity (0,1,1) */
+bar:nth-child(n+0)    /* same */
+bar:nth-child(n)      /* same */
+bar                   /* same but lower specificity (0,0,1) */
+
+ +

If b=0, then every ath element is picked. In +such a case, the b part may be omitted. + +

+

Examples:

+
tr:nth-child(2n+0) /* represents every even row of an HTML table */
+tr:nth-child(2n) /* same */
+
+ +

If both a and b are equal to zero, the +pseudo-class represents no element in the document tree.

+ +

The value a can be negative, but only the positive +values of an+b, for +n≥0, may represent an element in the document +tree.

+ +
+

Example:

+
html|tr:nth-child(-n+6)  /* represents the 6 first rows of XHTML tables */
+
+ +

When the value b is negative, the "+" character in the +expression must be removed (it is effectively replaced by the "-" +character indicating the negative value of b).

+ +
+

Examples:

+
:nth-child(10n-1)  /* represents the 9th, 19th, 29th, etc, element */
+:nth-child(10n+9)  /* Same */
+:nth-child(10n+-1) /* Syntactically invalid, and would be ignored */
+
+ + +
:nth-last-child() pseudo-class
+ +

The :nth-last-child(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings +after it in the document tree, for a given positive +integer or zero value of n, and has a parent element. See +:nth-child() pseudo-class for the syntax of its argument. +It also accepts the 'even' and 'odd' values +as arguments. + + +

+

Examples:

+
tr:nth-last-child(-n+2)    /* represents the two last rows of an HTML table */
+
+foo:nth-last-child(odd)    /* represents all odd foo elements in their parent element,
+                              counting from the last one */
+
+ + +
:nth-of-type() pseudo-class
+ +

The :nth-of-type(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings with the same +element name before it in the document tree, for a +given zero or positive integer value of n, and has a +parent element. In other words, this matches the bth child +of that type after all the children of that type have been split into +groups of a elements each. See :nth-child() pseudo-class +for the syntax of its argument. It also accepts the +'even' and 'odd' values. + + +

+

CSS example:

+

This allows an author to alternate the position of floated images:

+
img:nth-of-type(2n+1) { float: right; }
+img:nth-of-type(2n) { float: left; }
+
+ + +
:nth-last-of-type() pseudo-class
+ +

The :nth-last-of-type(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings with the same +element name after it in the document tree, for a +given zero or positive integer value of n, and has a +parent element. See :nth-child() pseudo-class for the +syntax of its argument. It also accepts the 'even' and 'odd' values. + + +

+

Example:

+

To represent all h2 children of an XHTML + body except the first and last, one could use the + following selector:

+
body > h2:nth-of-type(n+2):nth-last-of-type(n+2)
+

In this case, one could also use :not(), although the + selector ends up being just as long:

+
body > h2:not(:first-of-type):not(:last-of-type)
+
+ + +
:first-child pseudo-class
+ +

Same as :nth-child(1). The :first-child pseudo-class +represents an element that is the first child of some other element. + + +

+

Examples:

+

The following selector represents a p element that is + the first child of a div element:

+
div > p:first-child
+

This selector can represent the p inside the + div of the following fragment:

+
<p> The last P before the note.</p>
+<div class="note">
+   <p> The first P inside the note.</p>
+</div>
but cannot represent the second p in the following +fragment: +
<p> The last P before the note.</p>
+<div class="note">
+   <h2> Note </h2>
+   <p> The first P inside the note.</p>
+</div>
+

The following two selectors are usually equivalent:

+
* > a:first-child /* a is first child of any element */
+a:first-child /* Same (assuming a is not the root element) */
+
+ +
:last-child pseudo-class
+ +

Same as :nth-last-child(1). The :last-child pseudo-class +represents an element that is the last child of some other element. + +

+

Example:

+

The following selector represents a list item li that + is the last child of an ordered list ol. +

ol > li:last-child
+
+ +
:first-of-type pseudo-class
+ +

Same as :nth-of-type(1). The :first-of-type pseudo-class +represents an element that is the first sibling of its type in the list of +children of its parent element. + +

+

Example:

+

The following selector represents a definition title +dt inside a definition list dl, this +dt being the first of its type in the list of children of +its parent element.

+
dl dt:first-of-type
+

It is a valid description for the first two dt +elements in the following example but not for the third one:

+
<dl>
+ <dt>gigogne</dt>
+ <dd>
+  <dl>
+   <dt>fusée</dt>
+   <dd>multistage rocket</dd>
+   <dt>table</dt>
+   <dd>nest of tables</dd>
+  </dl>
+ </dd>
+</dl>
+
+ +
:last-of-type pseudo-class
+ +

Same as :nth-last-of-type(1). The +:last-of-type pseudo-class represents an element that is +the last sibling of its type in the list of children of its parent +element.

+ +
+

Example:

+

The following selector represents the last data cell + td of a table row.

+
tr > td:last-of-type
+
+ +
:only-child pseudo-class
+ +

Represents an element that has a parent element and whose parent +element has no other element children. Same as +:first-child:last-child or +:nth-child(1):nth-last-child(1), but with a lower +specificity.

+ +
:only-of-type pseudo-class
+ +

Represents an element that has a parent element and whose parent +element has no other element children with the same element name. Same +as :first-of-type:last-of-type or +:nth-of-type(1):nth-last-of-type(1), but with a lower +specificity.

+ + +
:empty pseudo-class
+ +

The :empty pseudo-class represents an element that has +no children at all. In terms of the DOM, only element nodes and text +nodes (including CDATA nodes and entity references) whose data has a +non-zero length must be considered as affecting emptiness; comments, +PIs, and other nodes must not affect whether an element is considered +empty or not.

+ +
+

Examples:

+

p:empty is a valid representation of the following fragment:

+
<p></p>
+

foo:empty is not a valid representation for the + following fragments:

+
<foo>bar</foo>
+
<foo><bar>bla</bar></foo>
+
<foo>this is not <bar>:empty</bar></foo>
+
+ +

6.6.6. Blank

+ +

This section intentionally left blank.

+ + +

6.6.7. The negation pseudo-class

+ +

The negation pseudo-class, :not(X), is a +functional notation taking a simple +selector (excluding the negation pseudo-class itself and +pseudo-elements) as an argument. It represents an element that is not +represented by the argument. + + + +

+

Examples:

+

The following CSS selector matches all button + elements in an HTML document that are not disabled.

+
button:not([DISABLED])
+

The following selector represents all but FOO + elements.

+
*:not(FOO)
+

The following group of selectors represents all HTML elements + except links.

+
html|*:not(:link):not(:visited)
+
+ +

Default namespace declarations do not affect the argument of the +negation pseudo-class unless the argument is a universal selector or a +type selector.

+ +
+

Examples:

+

Assuming that the default namespace is bound to + "http://example.com/", the following selector represents all + elements that are not in that namespace:

+
*|*:not(*)
+

The following CSS selector matches any element being hovered, + regardless of its namespace. In particular, it is not limited to + only matching elements in the default namespace that are not being + hovered, and elements not in the default namespace don't match the + rule when they are being hovered.

+
*|*:not(:hover)
+
+ +

Note: the :not() pseudo allows +useless selectors to be written. For instance :not(*|*), +which represents no element at all, or foo:not(bar), +which is equivalent to foo but with a higher +specificity.

+ +

7. Pseudo-elements

+ +

Pseudo-elements create abstractions about the document tree beyond +those specified by the document language. For instance, document +languages do not offer mechanisms to access the first letter or first +line of an element's content. Pseudo-elements allow designers to refer +to this otherwise inaccessible information. Pseudo-elements may also +provide designers a way to refer to content that does not exist in the +source document (e.g., the ::before and +::after pseudo-elements give access to generated +content).

+ +

A pseudo-element is made of two colons (::) followed +by the name of the pseudo-element.

+ +

This :: notation is introduced by the current document +in order to establish a discrimination between pseudo-classes and +pseudo-elements. For compatibility with existing style sheets, user +agents must also accept the previous one-colon notation for +pseudo-elements introduced in CSS levels 1 and 2 (namely, +:first-line, :first-letter, +:before and :after). This compatibility is +not allowed for the new pseudo-elements introduced in CSS level 3.

+ +

Only one pseudo-element may appear per selector, and if present it +must appear after the sequence of simple selectors that represents the +subjects of the selector. A +future version of this specification may allow multiple +pesudo-elements per selector.

+ +

7.1. The ::first-line pseudo-element

+ +

The ::first-line pseudo-element describes the contents +of the first formatted line of an element. + +

+

CSS example:

+
p::first-line { text-transform: uppercase }
+

The above rule means "change the letters of the first line of every +paragraph to uppercase".

+
+ +

The selector p::first-line does not match any real +HTML element. It does match a pseudo-element that conforming user +agents will insert at the beginning of every paragraph.

+ +

Note that the length of the first line depends on a number of +factors, including the width of the page, the font size, etc. Thus, +an ordinary HTML paragraph such as:

+ +
+<P>This is a somewhat long HTML 
+paragraph that will be broken into several 
+lines. The first line will be identified
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

the lines of which happen to be broken as follows: + +

+THIS IS A SOMEWHAT LONG HTML PARAGRAPH THAT
+will be broken into several lines. The first
+line will be identified by a fictional tag 
+sequence. The other lines will be treated as 
+ordinary lines in the paragraph.
+
+ +

This paragraph might be "rewritten" by user agents to include the +fictional tag sequence for ::first-line. This +fictional tag sequence helps to show how properties are inherited.

+ +
+<P><P::first-line> This is a somewhat long HTML 
+paragraph that </P::first-line> will be broken into several
+lines. The first line will be identified 
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

If a pseudo-element breaks up a real element, the desired effect +can often be described by a fictional tag sequence that closes and +then re-opens the element. Thus, if we mark up the previous paragraph +with a span element:

+ +
+<P><SPAN class="test"> This is a somewhat long HTML
+paragraph that will be broken into several
+lines.</SPAN> The first line will be identified
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

the user agent could simulate start and end tags for +span when inserting the fictional tag sequence for +::first-line. + +

+<P><P::first-line><SPAN class="test"> This is a
+somewhat long HTML
+paragraph that will </SPAN></P::first-line><SPAN class="test"> be
+broken into several
+lines.</SPAN> The first line will be identified
+by a fictional tag sequence. The other lines
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

In CSS, the ::first-line pseudo-element can only be +attached to a block-level element, an inline-block, a table-caption, +or a table-cell.

+ +

The "first formatted line" of an +element may occur inside a +block-level descendant in the same flow (i.e., a block-level +descendant that is not positioned and not a float). E.g., the first +line of the div in <DIV><P>This +line...</P></DIV> is the first line of the p (assuming +that both p and div are block-level). + +

The first line of a table-cell or inline-block cannot be the first +formatted line of an ancestor element. Thus, in <DIV><P +STYLE="display: inline-block">Hello<BR>Goodbye</P> +etcetera</DIV> the first formatted line of the +div is not the line "Hello". + +

Note that the first line of the p in this +fragment: <p><br>First... doesn't contain any +letters (assuming the default style for br in HTML +4). The word "First" is not on the first formatted line. + +

A UA should act as if the fictional start tags of the +::first-line pseudo-elements were nested just inside the +innermost enclosing block-level element. (Since CSS1 and CSS2 were +silent on this case, authors should not rely on this behavior.) Here +is an example. The fictional tag sequence for

+ +
+<DIV>
+  <P>First paragraph</P>
+  <P>Second paragraph</P>
+</DIV>
+
+ +

is

+ +
+<DIV>
+  <P><DIV::first-line><P::first-line>First paragraph</P::first-line></DIV::first-line></P>
+  <P><P::first-line>Second paragraph</P::first-line></P>
+</DIV>
+
+ +

The ::first-line pseudo-element is similar to an +inline-level element, but with certain restrictions. In CSS, the +following properties apply to a ::first-line +pseudo-element: font properties, color property, background +properties, 'word-spacing', 'letter-spacing', 'text-decoration', +'vertical-align', 'text-transform', 'line-height'. UAs may apply other +properties as well.

+ + +

7.2. The ::first-letter pseudo-element

+ +

The ::first-letter pseudo-element represents the first +letter of the first line of a block, if it is not preceded by any +other content (such as images or inline tables) on its line. The +::first-letter pseudo-element may be used for "initial caps" and "drop +caps", which are common typographical effects. This type of initial +letter is similar to an inline-level element if its 'float' property +is 'none'; otherwise, it is similar to a floated element.

+ +

In CSS, these are the properties that apply to ::first-letter +pseudo-elements: font properties, 'text-decoration', 'text-transform', +'letter-spacing', 'word-spacing' (when appropriate), 'line-height', +'float', 'vertical-align' (only if 'float' is 'none'), margin +properties, padding properties, border properties, color property, +background properties. UAs may apply other properties as well. To +allow UAs to render a typographically correct drop cap or initial cap, +the UA may choose a line-height, width and height based on the shape +of the letter, unlike for normal elements.

+ +
+

Example:

+

This example shows a possible rendering of an initial cap. Note +that the 'line-height' that is inherited by the ::first-letter +pseudo-element is 1.1, but the UA in this example has computed the +height of the first letter differently, so that it doesn't cause any +unnecessary space between the first two lines. Also note that the +fictional start tag of the first letter is inside the span, and thus +the font weight of the first letter is normal, not bold as the span: +

+p { line-height: 1.1 }
+p::first-letter { font-size: 3em; font-weight: normal }
+span { font-weight: bold }
+...
+<p><span>Het hemelsche</span> gerecht heeft zich ten lange lesten<br>
+Erbarremt over my en mijn benaeuwde vesten<br>
+En arme burgery, en op mijn volcx gebed<br>
+En dagelix geschrey de bange stad ontzet.
+
+
+

Image illustrating the ::first-letter pseudo-element +

+
+ +
+

The following CSS will make a drop cap initial letter span about two lines:

+ +
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<HTML>
+ <HEAD>
+  <TITLE>Drop cap initial letter</TITLE>
+  <STYLE type="text/css">
+   P               { font-size: 12pt; line-height: 1.2 }
+   P::first-letter { font-size: 200%; font-weight: bold; float: left }
+   SPAN            { text-transform: uppercase }
+  </STYLE>
+ </HEAD>
+ <BODY>
+  <P><SPAN>The first</SPAN> few words of an article
+    in The Economist.</P>
+ </BODY>
+</HTML>
+
+ +

This example might be formatted as follows:

+ +
+

Image illustrating the combined effect of the ::first-letter and ::first-line pseudo-elements

+
+ +

The fictional tag sequence is:

+ +
+<P>
+<SPAN>
+<P::first-letter>
+T
+</P::first-letter>he first
+</SPAN> 
+few words of an article in the Economist.
+</P>
+
+ +

Note that the ::first-letter pseudo-element tags abut +the content (i.e., the initial character), while the ::first-line +pseudo-element start tag is inserted right after the start tag of the +block element.

+ +

In order to achieve traditional drop caps formatting, user agents +may approximate font sizes, for example to align baselines. Also, the +glyph outline may be taken into account when formatting.

+ +

Punctuation (i.e, characters defined in Unicode in the "open" (Ps), +"close" (Pe), "initial" (Pi). "final" (Pf) and "other" (Po) +punctuation classes), that precedes or follows the first letter should +be included. [UNICODE]

+ +
+

Quotes that precede the
+first letter should be included.

+
+ +

The ::first-letter also applies if the first letter is +in fact a digit, e.g., the "6" in "67 million dollars is a lot of +money."

+ +

In CSS, the ::first-letter pseudo-element applies to +block, list-item, table-cell, table-caption, and inline-block +elements. A future version of this specification +may allow this pesudo-element to apply to more element +types.

+ +

The ::first-letter pseudo-element can be used with all +such elements that contain text, or that have a descendant in the same +flow that contains text. A UA should act as if the fictional start tag +of the ::first-letter pseudo-element is just before the first text of +the element, even if that first text is in a descendant.

+ +
+

Example:

+

The fictional tag sequence for this HTMLfragment: +

<div>
+<p>The first text.
+

is: +

<div>
+<p><div::first-letter><p::first-letter>T</...></...>he first text.
+
+ +

The first letter of a table-cell or inline-block cannot be the +first letter of an ancestor element. Thus, in <DIV><P +STYLE="display: inline-block">Hello<BR>Goodbye</P> +etcetera</DIV> the first letter of the div is not the +letter "H". In fact, the div doesn't have a first letter. + +

The first letter must occur on the first formatted line. For example, in +this fragment: <p><br>First... the first line +doesn't contain any letters and ::first-letter doesn't +match anything (assuming the default style for br in HTML +4). In particular, it does not match the "F" of "First." + +

In CSS, if an element is a list item ('display: list-item'), the +::first-letter applies to the first letter in the +principal box after the marker. UAs may ignore +::first-letter on list items with 'list-style-position: +inside'. If an element has ::before or +::after content, the ::first-letter applies +to the first letter of the element including that content. + +

+

Example:

+

After the rule 'p::before {content: "Note: "}', the selector +'p::first-letter' matches the "N" of "Note".

+
+ +

Some languages may have specific rules about how to treat certain +letter combinations. In Dutch, for example, if the letter combination +"ij" appears at the beginning of a word, both letters should be +considered within the ::first-letter pseudo-element. + +

If the letters that would form the ::first-letter are not in the +same element, such as "'T" in <p>'<em>T..., the UA +may create a ::first-letter pseudo-element from one of the elements, +both elements, or simply not create a pseudo-element.

+ +

Similarly, if the first letter(s) of the block are not at the start +of the line (for example due to bidirectional reordering), then the UA +need not create the pseudo-element(s). + +

+

Example:

+

The following example illustrates +how overlapping pseudo-elements may interact. The first letter of +each P element will be green with a font size of '24pt'. The rest of +the first formatted line will be 'blue' while the rest of the +paragraph will be 'red'.

+ +
p { color: red; font-size: 12pt }
+p::first-letter { color: green; font-size: 200% }
+p::first-line { color: blue }
+
+<P>Some text that ends up on two lines</P>
+ +

Assuming that a line break will occur before the word "ends", the +fictional tag +sequence for this fragment might be:

+ +
<P>
+<P::first-line>
+<P::first-letter> 
+S 
+</P::first-letter>ome text that 
+</P::first-line> 
+ends up on two lines 
+</P>
+ +

Note that the ::first-letter element is inside the ::first-line +element. Properties set on ::first-line are inherited by +::first-letter, but are overridden if the same property is set on +::first-letter.

+
+ + +

7.3. The ::selection pseudo-element

+ +

The ::selection pseudo-element applies to the portion +of a document that has been highlighted by the user. This also +applies, for example, to selected text within an editable text +field. This pseudo-element should not be confused with the :checked pseudo-class (which used to be +named :selected) + +

Although the ::selection pseudo-element is dynamic in +nature, and is altered by user action, it is reasonable to expect that +when a UA re-renders to a static medium (such as a printed page, see +[CSS21]) which was originally rendered to a +dynamic medium (like screen), the UA may wish to transfer the current +::selection state to that other medium, and have all the +appropriate formatting and rendering take effect as well. This is not +required — UAs may omit the ::selection +pseudo-element for static media. + +

These are the CSS properties that apply to ::selection +pseudo-elements: color, background, cursor (optional), outline +(optional). The computed value of the 'background-image' property on +::selection may be ignored. + + +

7.4. The ::before and ::after pseudo-elements

+ +

The ::before and ::after pseudo-elements +can be used to describe generated content before or after an element's +content. They are explained in CSS 2.1 [CSS21].

+ +

When the ::first-letter and ::first-line +pseudo-elements are combined with ::before and +::after, they apply to the first letter or line of the +element including the inserted text.

+ +

8. Combinators

+ +

8.1. Descendant combinator

+ +

At times, authors may want selectors to describe an element that is +the descendant of another element in the document tree (e.g., "an +EM element that is contained within an H1 +element"). Descendant combinators express such a relationship. A +descendant combinator is white space that +separates two sequences of simple selectors. A selector of the form +"A B" represents an element B that is an +arbitrary descendant of some ancestor element A. + +

+

Examples:

+

For example, consider the following selector:

+
h1 em
+

It represents an em element being the descendant of + an h1 element. It is a correct and valid, but partial, + description of the following fragment:

+
<h1>This <span class="myclass">headline
+is <em>very</em> important</span></h1>
+

The following selector:

+
div * p
+

represents a p element that is a grandchild or later + descendant of a div element. Note the whitespace on + either side of the "*" is not part of the universal selector; the + whitespace is a combinator indicating that the DIV must be the + ancestor of some element, and that that element must be an ancestor + of the P.

+

The following selector, which combines descendant combinators and + attribute selectors, represents an + element that (1) has the href attribute set and (2) is + inside a p that is itself inside a div:

+
div p *[href]
+
+ +

8.2. Child combinators

+ +

A child combinator describes a childhood relationship +between two elements. A child combinator is made of the +"greater-than sign" (>) character and +separates two sequences of simple selectors. + + +

+

Examples:

+

The following selector represents a p element that is + child of body:

+
body > p
+

The following example combines descendant combinators and child + combinators.

+
div ol>li p
+

It represents a p element that is a descendant of an + li element; the li element must be the + child of an ol element; the ol element must + be a descendant of a div. Notice that the optional white + space around the ">" combinator has been left out.

+
+ +

For information on selecting the first child of an element, please +see the section on the :first-child pseudo-class +above.

+ +

8.3. Sibling combinators

+ +

There are two different sibling combinators: the adjacent sibling +combinator and the general sibling combinator. In both cases, +non-element nodes (e.g. text between elements) are ignored when +considering adjacency of elements.

+ +

8.3.1. Adjacent sibling combinator

+ +

The adjacent sibling combinator is made of the "plus +sign" (U+002B, +) character that separates two +sequences of simple selectors. The elements represented by the two +sequences share the same parent in the document tree and the element +represented by the first sequence immediately precedes the element +represented by the second one.

+ +
+

Examples:

+

The following selector represents a p element + immediately following a math element:

+
math + p
+

The following selector is conceptually similar to the one in the + previous example, except that it adds an attribute selector — it + adds a constraint to the h1 element, that it must have + class="opener":

+
h1.opener + h2
+
+ + +

8.3.2. General sibling combinator

+ +

The general sibling combinator is made of the "tilde" +(U+007E, ~) character that separates two sequences of +simple selectors. The elements represented by the two sequences share +the same parent in the document tree and the element represented by +the first sequence precedes (not necessarily immediately) the element +represented by the second one.

+ +
+

Example:

+
h1 ~ pre
+

represents a pre element following an h1. It + is a correct and valid, but partial, description of:

+
<h1>Definition of the function a</h1>
+<p>Function a(x) has to be applied to all figures in the table.</p>
+<pre>function a(x) = 12x/13.5</pre>
+
+ +

9. Calculating a selector's specificity

+ +

A selector's specificity is calculated as follows:

+ + + +

Selectors inside the negation pseudo-class +are counted like any other, but the negation itself does not count as +a pseudo-class.

+ +

Concatenating the three numbers a-b-c (in a number system with a +large base) gives the specificity.

+ +
+

Examples:

+
*               /* a=0 b=0 c=0 -> specificity =   0 */
+LI              /* a=0 b=0 c=1 -> specificity =   1 */
+UL LI           /* a=0 b=0 c=2 -> specificity =   2 */
+UL OL+LI        /* a=0 b=0 c=3 -> specificity =   3 */
+H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity =  11 */
+UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */
+LI.red.level    /* a=0 b=2 c=1 -> specificity =  21 */
+#x34y           /* a=1 b=0 c=0 -> specificity = 100 */
+#s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 101 */
+
+
+ +

Note: the specificity of the styles +specified in an HTML style attribute is described in CSS +2.1. [CSS21].

+ +

10. The grammar of Selectors

+ +

10.1. Grammar

+ +

The grammar below defines the syntax of Selectors. It is globally +LL(1) and can be locally LL(2) (but note that most UA's should not use +it directly, since it doesn't express the parsing conventions). The +format of the productions is optimized for human consumption and some +shorthand notations beyond Yacc (see [YACC]) +are used:

+ + + +

The productions are:

+ +
selectors_group
+  : selector [ COMMA S* selector ]*
+  ;
+
+selector
+  : simple_selector_sequence [ combinator simple_selector_sequence ]*
+  ;
+
+combinator
+  /* combinators can be surrounded by white space */
+  : PLUS S* | GREATER S* | TILDE S* | S+
+  ;
+
+simple_selector_sequence
+  : [ type_selector | universal ]
+    [ HASH | class | attrib | pseudo | negation ]*
+  | [ HASH | class | attrib | pseudo | negation ]+
+  ;
+
+type_selector
+  : [ namespace_prefix ]? element_name
+  ;
+
+namespace_prefix
+  : [ IDENT | '*' ]? '|'
+  ;
+
+element_name
+  : IDENT
+  ;
+
+universal
+  : [ namespace_prefix ]? '*'
+  ;
+
+class
+  : '.' IDENT
+  ;
+
+attrib
+  : '[' S* [ namespace_prefix ]? IDENT S*
+        [ [ PREFIXMATCH |
+            SUFFIXMATCH |
+            SUBSTRINGMATCH |
+            '=' |
+            INCLUDES |
+            DASHMATCH ] S* [ IDENT | STRING ] S*
+        ]? ']'
+  ;
+
+pseudo
+  /* '::' starts a pseudo-element, ':' a pseudo-class */
+  /* Exceptions: :first-line, :first-letter, :before and :after. */
+  /* Note that pseudo-elements are restricted to one per selector and */
+  /* occur only in the last simple_selector_sequence. */
+  : ':' ':'? [ IDENT | functional_pseudo ]
+  ;
+
+functional_pseudo
+  : FUNCTION S* expression ')'
+  ;
+
+expression
+  /* In CSS3, the expressions are identifiers, strings, */
+  /* or of the form "an+b" */
+  : [ [ PLUS | '-' | DIMENSION | NUMBER | STRING | IDENT ] S* ]+
+  ;
+
+negation
+  : NOT S* negation_arg S* ')'
+  ;
+
+negation_arg
+  : type_selector | universal | HASH | class | attrib | pseudo
+  ;
+ + +

10.2. Lexical scanner

+ +

The following is the tokenizer, written in Flex (see +[FLEX]) notation. The tokenizer is +case-insensitive.

+ +

The two occurrences of "\377" represent the highest character +number that current versions of Flex can deal with (decimal 255). They +should be read as "\4177777" (decimal 1114111), which is the highest +possible code point in Unicode/ISO-10646. [UNICODE]

+ +
%option case-insensitive
+
+ident     [-]?{nmstart}{nmchar}*
+name      {nmchar}+
+nmstart   [_a-z]|{nonascii}|{escape}
+nonascii  [^\0-\177]
+unicode   \\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?
+escape    {unicode}|\\[^\n\r\f0-9a-f]
+nmchar    [_a-z0-9-]|{nonascii}|{escape}
+num       [0-9]+|[0-9]*\.[0-9]+
+string    {string1}|{string2}
+string1   \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*\"
+string2   \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*\'
+invalid   {invalid1}|{invalid2}
+invalid1  \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*
+invalid2  \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*
+nl        \n|\r\n|\r|\f
+w         [ \t\r\n\f]*
+
+%%
+
+[ \t\r\n\f]+     return S;
+
+"~="             return INCLUDES;
+"|="             return DASHMATCH;
+"^="             return PREFIXMATCH;
+"$="             return SUFFIXMATCH;
+"*="             return SUBSTRINGMATCH;
+{ident}          return IDENT;
+{string}         return STRING;
+{ident}"("       return FUNCTION;
+{num}            return NUMBER;
+"#"{name}        return HASH;
+{w}"+"           return PLUS;
+{w}">"           return GREATER;
+{w}","           return COMMA;
+{w}"~"           return TILDE;
+":not("          return NOT;
+@{ident}         return ATKEYWORD;
+{invalid}        return INVALID;
+{num}%           return PERCENTAGE;
+{num}{ident}     return DIMENSION;
+"<!--"           return CDO;
+"-->"            return CDC;
+
+"url("{w}{string}{w}")"                           return URI;
+"url("{w}([!#$%&*-~]|{nonascii}|{escape})*{w}")"  return URI;
+U\+[0-9a-f?]{1,6}(-[0-9a-f]{1,6})?                return UNICODE_RANGE;
+
+\/\*[^*]*\*+([^/*][^*]*\*+)*\/                    /* ignore comments */
+
+.                return *yytext;
+ + + +

11. Namespaces and down-level clients

+ +

An important issue is the interaction of CSS selectors with XML +documents in web clients that were produced prior to this +document. Unfortunately, due to the fact that namespaces must be +matched based on the URI which identifies the namespace, not the +namespace prefix, some mechanism is required to identify namespaces in +CSS by their URI as well. Without such a mechanism, it is impossible +to construct a CSS style sheet which will properly match selectors in +all cases against a random set of XML documents. However, given +complete knowledge of the XML document to which a style sheet is to be +applied, and a limited use of namespaces within the XML document, it +is possible to construct a style sheet in which selectors would match +elements and attributes correctly.

+ +

It should be noted that a down-level CSS client will (if it +properly conforms to CSS forward compatible parsing rules) ignore all +@namespace at-rules, as well as all style rules that make +use of namespace qualified element type or attribute selectors. The +syntax of delimiting namespace prefixes in CSS was deliberately chosen +so that down-level CSS clients would ignore the style rules rather +than possibly match them incorrectly.

+ +

The use of default namespaces in CSS makes it possible to write +element type selectors that will function in both namespace aware CSS +clients as well as down-level clients. It should be noted that +down-level clients may incorrectly match selectors against XML +elements in other namespaces.

+ +

The following are scenarios and examples in which it is possible to +construct style sheets which would function properly in web clients +that do not implement this proposal.

+ +
    +
  1. + +

    The XML document does not use namespaces.

    + +
      + +
    • In this case, it is obviously not necessary to declare or use + namespaces in the style sheet. Standard CSS element type and + attribute selectors will function adequately in a down-level + client.
    • + +
    • In a CSS namespace aware client, the default behavior of + element selectors matching without regard to namespace will + function properly against all elements, since no namespaces are + present. However, the use of specific element type selectors that + match only elements that have no namespace ("|name") + will guarantee that selectors will match only XML elements that do + not have a declared namespace.
    • + +
    + +
  2. + +
  3. + +

    The XML document defines a single, default namespace used + throughout the document. No namespace prefixes are used in element + names.

    + +
      + +
    • In this case, a down-level client will function as if + namespaces were not used in the XML document at all. Standard CSS + element type and attribute selectors will match against all + elements.
    • + +
    + +
  4. + +
  5. + +

    The XML document does not use a default namespace, all + namespace prefixes used are known to the style sheet author, and + there is a direct mapping between namespace prefixes and namespace + URIs. (A given prefix may only be mapped to one namespace URI + throughout the XML document; there may be multiple prefixes mapped + to the same URI).

    + +
      + +
    • In this case, the down-level client will view and match + element type and attribute selectors based on their fully + qualified name, not the local part as outlined in the Type selectors and Namespaces section. CSS + selectors may be declared using an escaped colon "\:" + to describe the fully qualified names, e.g. + "html\:h1" will match + <html:h1>. Selectors using the qualified name + will only match XML elements that use the same prefix. Other + namespace prefixes used in the XML that are mapped to the same URI + will not match as expected unless additional CSS style rules are + declared for them.
    • + +
    • Note that selectors declared in this fashion will + only match in down-level clients. A CSS namespace aware + client will match element type and attribute selectors based on + the name's local part. Selectors declared with the fully + qualified name will not match (unless there is no namespace prefix + in the fully qualified name).
    • + +
    + +
  6. + +
+ +

In other scenarios: when the namespace prefixes used in the XML are +not known in advance by the style sheet author; or a combination of +elements with no namespace are used in conjunction with elements using +a default namespace; or the same namespace prefix is mapped to +different namespace URIs within the same document, or in +different documents; it is impossible to construct a CSS style sheet +that will function properly against all elements in those documents, +unless, the style sheet is written using a namespace URI syntax (as +outlined in this document or similar) and the document is processed by +a CSS and XML namespace aware client.

+ +

12. Profiles

+ +

Each specification using Selectors must define the subset of W3C +Selectors it allows and excludes, and describe the local meaning of +all the components of that subset.

+ +

Non normative examples: + +

+ + + + + + + + + + + + + + + +
Selectors profile
SpecificationCSS level 1
Acceptstype selectors
class selectors
ID selectors
:link, + :visited and :active pseudo-classes
descendant combinator +
::first-line and ::first-letter pseudo-elements
Excludes + +

universal selector
attribute selectors
:hover and :focus + pseudo-classes
:target pseudo-class
:lang() pseudo-class
all UI + element states pseudo-classes
all structural + pseudo-classes
negation pseudo-class
all + UI element fragments pseudo-elements
::before and ::after + pseudo-elements
child combinators
sibling combinators + +

namespaces

Extra constraintsonly one class selector allowed per sequence of simple + selectors


+ + + + + + + + + + + + + + + +
Selectors profile
SpecificationCSS level 2
Acceptstype selectors
universal selector
attribute presence and + values selectors
class selectors
ID selectors
:link, :visited, + :active, :hover, :focus, :lang() and :first-child pseudo-classes +
descendant combinator
child combinator
adjacent sibling + combinator
::first-line and ::first-letter pseudo-elements
::before + and ::after pseudo-elements
Excludes + +

content selectors
substring matching attribute + selectors
:target pseudo-classes
all UI element + states pseudo-classes
all structural pseudo-classes other + than :first-child
negation pseudo-class
all UI element + fragments pseudo-elements
general sibling combinators + +

namespaces

Extra constraintsmore than one class selector per sequence of simple selectors (CSS1 + constraint) allowed
+ +

In CSS, selectors express pattern matching rules that determine which style +rules apply to elements in the document tree. + +

The following selector (CSS level 2) will match all anchors a +with attribute name set inside a section 1 header h1: +

h1 a[name]
+ +

All CSS declarations attached to such a selector are applied to elements +matching it.

+ +
+ + + + + + + + + + + + + + + + +
Selectors profile
SpecificationSTTS 3
Accepts + +

type selectors
universal selectors
attribute selectors
class + selectors
ID selectors
all structural pseudo-classes
+ all combinators + +

namespaces

Excludesnon-accepted pseudo-classes
pseudo-elements
Extra constraintssome selectors and combinators are not allowed in fragment + descriptions on the right side of STTS declarations.
+ +

Selectors can be used in STTS 3 in two different + manners: +

    +
  1. a selection mechanism equivalent to CSS selection mechanism: declarations + attached to a given selector are applied to elements matching that selector, +
  2. fragment descriptions that appear on the right side of declarations. +
+ +

13. Conformance and requirements

+ +

This section defines conformance with the present specification only. + +

The inability of a user agent to implement part of this specification due to +the limitations of a particular device (e.g., non interactive user agents will +probably not implement dynamic pseudo-classes because they make no sense without +interactivity) does not imply non-conformance. + +

All specifications reusing Selectors must contain a Profile listing the +subset of Selectors it accepts or excludes, and describing the constraints +it adds to the current specification. + +

Invalidity is caused by a parsing error, e.g. an unrecognized token or a token +which is not allowed at the current parsing point. + +

User agents must observe the rules for handling parsing errors: +

+ +

Specifications reusing Selectors must define how to handle parsing +errors. (In the case of CSS, the entire rule in which the selector is +used is dropped.)

+ + + +

14. Tests

+ +

This specification has a test +suite allowing user agents to verify their basic conformance to +the specification. This test suite does not pretend to be exhaustive +and does not cover all possible combined cases of Selectors.

+ +

15. Acknowledgements

+ +

The CSS working group would like to thank everyone who has sent +comments on this specification over the years.

+ +

The working group would like to extend special thanks to Donna +McManus, Justin Baker, Joel Sklar, and Molly Ives Brower who perfermed +the final editorial review.

+ +

16. References

+ +
+ +
[CSS1] +
Bert Bos, Håkon Wium Lie; "Cascading Style Sheets, level 1", W3C Recommendation, 17 Dec 1996, revised 11 Jan 1999 +
(http://www.w3.org/TR/REC-CSS1) + +
[CSS21] +
Bert Bos, Tantek Çelik, Ian Hickson, Håkon Wium Lie, editors; "Cascading Style Sheets, level 2 revision 1", W3C Working Draft, 13 June 2005 +
(http://www.w3.org/TR/CSS21) + +
[CWWW] +
Martin J. Dürst, François Yergeau, Misha Wolf, Asmus Freytag, Tex Texin, editors; "Character Model for the World Wide Web", W3C Recommendation, 15 February 2005 +
(http://www.w3.org/TR/charmod/) + +
[FLEX] +
"Flex: The Lexical Scanner Generator", Version 2.3.7, ISBN 1882114213 + +
[HTML4] +
Dave Ragget, Arnaud Le Hors, Ian Jacobs, editors; "HTML 4.01 Specification", W3C Recommendation, 24 December 1999 +
(http://www.w3.org/TR/html4/) + +
[MATH] +
Patrick Ion, Robert Miner, editors; "Mathematical Markup Language (MathML) 1.01", W3C Recommendation, revision of 7 July 1999 +
(http://www.w3.org/TR/REC-MathML/) + +
[RFC3066] +
H. Alvestrand; "Tags for the Identification of Languages", Request for Comments 3066, January 2001 +
(http://www.ietf.org/rfc/rfc3066.txt) + +
[STTS] +
Daniel Glazman; "Simple Tree Transformation Sheets 3", Electricité de France, submission to the W3C, 11 November 1998 +
(http://www.w3.org/TR/NOTE-STTS3) + +
[SVG] +
Jon Ferraiolo, 藤沢 淳, Dean Jackson, editors; "Scalable Vector Graphics (SVG) 1.1 Specification", W3C Recommendation, 14 January 2003 +
(http://www.w3.org/TR/SVG/) + +
[UNICODE]
+
The Unicode Standard, Version 4.1, The Unicode Consortium. Boston, MA, Addison-Wesley, March 2005. ISBN 0-321-18578-1, as amended by Unicode 4.0.1 and Unicode 4.1.0. +
(http://www.unicode.org/versions/)
+ +
[XML10] +
Tim Bray, Jean Paoli, C. M. Sperberg-McQueen, Eve Maler, François Yergeau, editors; "Extensible Markup Language (XML) 1.0 (Third Edition)", W3C Recommendation, 4 February 2004 +
(http://www.w3.org/TR/REC-xml/) + +
[XMLNAMES] +
Tim Bray, Dave Hollander, Andrew Layman, editors; "Namespaces in XML", W3C Recommendation, 14 January 1999 +
(http://www.w3.org/TR/REC-xml-names/) + +
[YACC] +
S. C. Johnson; "YACC — Yet another compiler compiler", Technical Report, Murray Hill, 1975 + +
+ +
+ test +
+
+
+ test +
+ test +
+
+
+ test +
+
+
+
+ +
+ d1d1 + d2d2 + d3d3 + d4d4 + d5d5 + d6d6 + + + + + + +
+
+ d1 + d1 + + d2 + d2 + + d3 + d3 + + d4 + d4 + + d5 + d5 + + d6 + d6 + +
+ + + diff --git a/test_new/browser/fixtures/slick/template-transitional.html b/test_new/browser/fixtures/slick/template-transitional.html new file mode 100644 index 0000000..f6a91a3 --- /dev/null +++ b/test_new/browser/fixtures/slick/template-transitional.html @@ -0,0 +1,2932 @@ + + + + + + + + template xhtml as html + + + +
+

W3C + +

Selectors

+ +

W3C Working Draft 15 December 2005

+ +
+ +
This version: + +
+ http://www.w3.org/TR/2005/WD-css3-selectors-20051215 + +
Latest version: + +
+ http://www.w3.org/TR/css3-selectors + +
Previous version: + +
+ http://www.w3.org/TR/2001/CR-css3-selectors-20011113 + +
Editors: + +
Daniel Glazman (Invited Expert)
+ +
Tantek Çelik (Invited Expert) + +
Ian Hickson (Google) + +
Peter Linss (former editor, Netscape/AOL) + +
John Williams (former editor, Quark, Inc.) + +
+ +
+ +
+ +

Abstract

+ +

Selectors are patterns that match against elements in a + tree. Selectors have been optimized for use with HTML and XML, and + are designed to be usable in performance-critical code.

+ +

CSS (Cascading + Style Sheets) is a language for describing the rendering of HTML and XML documents on + screen, on paper, in speech, etc. CSS uses Selectors for binding + style properties to elements in the document. This document + describes extensions to the selectors defined in CSS level 2. These + extended selectors will be used by CSS level 3. + +

Selectors define the following function:

+ +
expression ∗ element → boolean
+ +

That is, given an element and a selector, this specification + defines whether that element matches the selector.

+ +

These expressions can also be used, for instance, to select a set + of elements, or a single element from a set of elements, by + evaluating the expression across all the elements in a + subtree. STTS (Simple Tree Transformation Sheets), a + language for transforming XML trees, uses this mechanism. [STTS]

+ +

Status of this document

+ +

This section describes the status of this document at the + time of its publication. Other documents may supersede this + document. A list of current W3C publications and the latest revision + of this technical report can be found in the W3C technical reports index at + http://www.w3.org/TR/.

+ +

This document describes the selectors that already exist in CSS1 and CSS2, and + also proposes new selectors for CSS3 and other languages that may need them.

+ +

The CSS Working Group doesn't expect that all implementations of + CSS3 will have to implement all selectors. Instead, there will + probably be a small number of variants of CSS3, called profiles. For + example, it may be that only a profile for interactive user agents + will include all of the selectors.

+ +

This specification is a last call working draft for the the CSS Working Group + (Style Activity). This + document is a revision of the Candidate + Recommendation dated 2001 November 13, and has incorporated + implementation feedback received in the past few years. It is + expected that this last call will proceed straight to Proposed + Recommendation stage since it is believed that interoperability will + be demonstrable.

+ +

All persons are encouraged to review and implement this + specification and return comments to the (archived) + public mailing list www-style + (see instructions). W3C + Members can also send comments directly to the CSS Working + Group. + The deadline for comments is 14 January 2006.

+ +

This is still a draft document and may be updated, replaced, or + obsoleted by other documents at any time. It is inappropriate to + cite a W3C Working Draft as other than "work in progress". + +

This document may be available in translation. + The English version of this specification is the only normative + version. + +

+ +

Table of contents

+ + + +
+ +

1. Introduction

+ +

1.1. Dependencies

+ +

Some features of this specification are specific to CSS, or have + particular limitations or rules specific to CSS. In this + specification, these have been described in terms of CSS2.1. [CSS21]

+ +

1.2. Terminology

+ +

All of the text of this specification is normative except + examples, notes, and sections explicitly marked as + non-normative.

+ +

1.3. Changes from CSS2

+ +

This section is non-normative.

+ +

The main differences between the selectors in CSS2 and those in + Selectors are: + +

+ +

2. Selectors

+ +

This section is non-normative, as it merely summarizes the +following sections.

+ +

A Selector represents a structure. This structure can be used as a +condition (e.g. in a CSS rule) that determines which elements a +selector matches in the document tree, or as a flat description of the +HTML or XML fragment corresponding to that structure.

+ +

Selectors may range from simple element names to rich contextual +representations.

+ +

The following table summarizes the Selector syntax:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PatternMeaningDescribed in sectionFirst defined in CSS level
*any elementUniversal + selector2
Ean element of type EType selector1
E[foo]an E element with a "foo" attributeAttribute + selectors2
E[foo="bar"]an E element whose "foo" attribute value is exactly + equal to "bar"Attribute + selectors2
E[foo~="bar"]an E element whose "foo" attribute value is a list of + space-separated values, one of which is exactly equal to "bar"Attribute + selectors2
E[foo^="bar"]an E element whose "foo" attribute value begins exactly + with the string "bar"Attribute + selectors3
E[foo$="bar"]an E element whose "foo" attribute value ends exactly + with the string "bar"Attribute + selectors3
E[foo*="bar"]an E element whose "foo" attribute value contains the + substring "bar"Attribute + selectors3
E[hreflang|="en"]an E element whose "hreflang" attribute has a hyphen-separated + list of values beginning (from the left) with "en"Attribute + selectors2
E:rootan E element, root of the documentStructural + pseudo-classes3
E:nth-child(n)an E element, the n-th child of its parentStructural + pseudo-classes3
E:nth-last-child(n)an E element, the n-th child of its parent, counting + from the last oneStructural + pseudo-classes3
E:nth-of-type(n)an E element, the n-th sibling of its typeStructural + pseudo-classes3
E:nth-last-of-type(n)an E element, the n-th sibling of its type, counting + from the last oneStructural + pseudo-classes3
E:first-childan E element, first child of its parentStructural + pseudo-classes2
E:last-childan E element, last child of its parentStructural + pseudo-classes3
E:first-of-typean E element, first sibling of its typeStructural + pseudo-classes3
E:last-of-typean E element, last sibling of its typeStructural + pseudo-classes3
E:only-childan E element, only child of its parentStructural + pseudo-classes3
E:only-of-typean E element, only sibling of its typeStructural + pseudo-classes3
E:emptyan E element that has no children (including text + nodes)Structural + pseudo-classes3
E:link
E:visited
an E element being the source anchor of a hyperlink of + which the target is not yet visited (:link) or already visited + (:visited)The link + pseudo-classes1
E:active
E:hover
E:focus
an E element during certain user actionsThe user + action pseudo-classes1 and 2
E:targetan E element being the target of the referring URIThe target + pseudo-class3
E:lang(fr)an element of type E in language "fr" (the document + language specifies how language is determined)The :lang() + pseudo-class2
E:enabled
E:disabled
a user interface element E which is enabled or + disabledThe UI element states + pseudo-classes3
E:checkeda user interface element E which is checked (for instance a radio-button or checkbox)The UI element states + pseudo-classes3
E::first-linethe first formatted line of an E elementThe ::first-line + pseudo-element1
E::first-letterthe first formatted letter of an E elementThe ::first-letter + pseudo-element1
E::selectionthe portion of an E element that is currently + selected/highlighted by the userThe UI element + fragments pseudo-elements3
E::beforegenerated content before an E elementThe ::before + pseudo-element2
E::aftergenerated content after an E elementThe ::after + pseudo-element2
E.warningan E element whose class is +"warning" (the document language specifies how class is determined).Class + selectors1
E#myidan E element with ID equal to "myid".ID + selectors1
E:not(s)an E element that does not match simple selector sNegation + pseudo-class3
E Fan F element descendant of an E elementDescendant + combinator1
E > Fan F element child of an E elementChild + combinator2
E + Fan F element immediately preceded by an E elementAdjacent sibling combinator2
E ~ Fan F element preceded by an E elementGeneral sibling combinator3
+ +

The meaning of each selector is derived from the table above by +prepending "matches" to the contents of each cell in the "Meaning" +column.

+ +

3. Case sensitivity

+ +

The case sensitivity of document language element names, attribute +names, and attribute values in selectors depends on the document +language. For example, in HTML, element names are case-insensitive, +but in XML, they are case-sensitive.

+ +

4. Selector syntax

+ +

A selector is a chain of one +or more sequences of simple selectors +separated by combinators.

+ +

A sequence of simple selectors +is a chain of simple selectors +that are not separated by a combinator. It +always begins with a type selector or a +universal selector. No other type +selector or universal selector is allowed in the sequence.

+ +

A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, content selector, or pseudo-class. One pseudo-element may be appended to the last +sequence of simple selectors.

+ +

Combinators are: white space, "greater-than +sign" (U+003E, >), "plus sign" (U+002B, ++) and "tilde" (U+007E, ~). White +space may appear between a combinator and the simple selectors around +it. Only the characters "space" (U+0020), "tab" +(U+0009), "line feed" (U+000A), "carriage return" (U+000D), and "form +feed" (U+000C) can occur in white space. Other space-like characters, +such as "em-space" (U+2003) and "ideographic space" (U+3000), are +never part of white space.

+ +

The elements of a document tree that are represented by a selector +are the subjects of the selector. A +selector consisting of a single sequence of simple selectors +represents any element satisfying its requirements. Prepending another +sequence of simple selectors and a combinator to a sequence imposes +additional matching constraints, so the subjects of a selector are +always a subset of the elements represented by the last sequence of +simple selectors.

+ +

An empty selector, containing no sequence of simple selectors and +no pseudo-element, is an invalid +selector.

+ +

5. Groups of selectors

+ +

When several selectors share the same declarations, they may be +grouped into a comma-separated list. (A comma is U+002C.)

+ +
+

CSS examples:

+

In this example, we condense three rules with identical +declarations into one. Thus,

+
h1 { font-family: sans-serif }
+h2 { font-family: sans-serif }
+h3 { font-family: sans-serif }
+

is equivalent to:

+
h1, h2, h3 { font-family: sans-serif }
+
+ +

Warning: the equivalence is true in this example +because all the selectors are valid selectors. If just one of these +selectors were invalid, the entire group of selectors would be +invalid. This would invalidate the rule for all three heading +elements, whereas in the former case only one of the three individual +heading rules would be invalidated.

+ + +

6. Simple selectors

+ +

6.1. Type selector

+ +

A type selector is the name of a document language +element type. A type selector represents an instance of the element +type in the document tree.

+ +
+

Example:

+

The following selector represents an h1 element in the document tree:

+
h1
+
+ + +

6.1.1. Type selectors and namespaces

+ +

Type selectors allow an optional namespace ([XMLNAMES]) component. A namespace prefix +that has been previously declared may be prepended to the element name +separated by the namespace separator "vertical bar" +(U+007C, |).

+ +

The namespace component may be left empty to indicate that the +selector is only to represent elements with no declared namespace.

+ +

An asterisk may be used for the namespace prefix, indicating that +the selector represents elements in any namespace (including elements +with no namespace).

+ +

Element type selectors that have no namespace component (no +namespace separator), represent elements without regard to the +element's namespace (equivalent to "*|") unless a default +namespace has been declared. If a default namespace has been declared, +the selector will represent only elements in the default +namespace.

+ +

A type selector containing a namespace prefix that has not been +previously declared is an invalid selector. +The mechanism for declaring a namespace prefix is left up to the +language implementing Selectors. In CSS, such a mechanism is defined +in the General Syntax module.

+ +

In a namespace-aware client, element type selectors will only match +against the local part +of the element's qualified +name. See below for notes about matching +behaviors in down-level clients.

+ +

In summary:

+ +
+
ns|E
+
elements with name E in namespace ns
+
*|E
+
elements with name E in any namespace, including those without any + declared namespace
+
|E
+
elements with name E without any declared namespace
+
E
+
if no default namespace has been specified, this is equivalent to *|E. + Otherwise it is equivalent to ns|E where ns is the default namespace.
+
+ +
+

CSS examples:

+ +
@namespace foo url(http://www.example.com);
+ foo|h1 { color: blue }
+ foo|* { color: yellow }
+ |h1 { color: red }
+ *|h1 { color: green }
+ h1 { color: green }
+ +

The first rule will match only h1 elements in the + "http://www.example.com" namespace.

+ +

The second rule will match all elements in the + "http://www.example.com" namespace.

+ +

The third rule will match only h1 elements without + any declared namespace.

+ +

The fourth rule will match h1 elements in any + namespace (including those without any declared namespace).

+ +

The last rule is equivalent to the fourth rule because no default + namespace has been defined.

+ +
+ +

6.2. Universal selector

+ +

The universal selector, written "asterisk" +(*), represents the qualified name of any element +type. It represents any single element in the document tree in any +namespace (including those without any declared namespace) if no +default namespace has been specified. If a default namespace has been +specified, see Universal selector and +Namespaces below.

+ +

If the universal selector is not the only component of a sequence +of simple selectors, the * may be omitted.

+ +
+

Examples:

+
    +
  • *[hreflang|=en] and [hreflang|=en] are equivalent,
  • +
  • *.warning and .warning are equivalent,
  • +
  • *#myid and #myid are equivalent.
  • +
+
+ +

Note: it is recommended that the +*, representing the universal selector, not be +omitted.

+ +

6.2.1. Universal selector and namespaces

+ +

The universal selector allows an optional namespace component. It +is used as follows:

+ +
+
ns|*
+
all elements in namespace ns
+
*|*
+
all elements
+
|*
+
all elements without any declared namespace
+
*
+
if no default namespace has been specified, this is equivalent to *|*. + Otherwise it is equivalent to ns|* where ns is the default namespace.
+
+ +

A universal selector containing a namespace prefix that has not +been previously declared is an invalid +selector. The mechanism for declaring a namespace prefix is left up +to the language implementing Selectors. In CSS, such a mechanism is +defined in the General Syntax module.

+ + +

6.3. Attribute selectors

+ +

Selectors allow the representation of an element's attributes. When +a selector is used as an expression to match against an element, +attribute selectors must be considered to match an element if that +element has an attribute that matches the attribute represented by the +attribute selector.

+ +

6.3.1. Attribute presence and values +selectors

+ +

CSS2 introduced four attribute selectors:

+ +
+
[att] +
Represents an element with the att attribute, whatever the value of + the attribute.
+
[att=val]
+
Represents an element with the att attribute whose value is exactly + "val".
+
[att~=val]
+
Represents an element with the att attribute whose value is a whitespace-separated list of words, one of + which is exactly "val". If "val" contains whitespace, it will never + represent anything (since the words are separated by + spaces).
+
[att|=val] +
Represents an element with the att attribute, its value either + being exactly "val" or beginning with "val" immediately followed by + "-" (U+002D). This is primarily intended to allow language subcode + matches (e.g., the hreflang attribute on the + link element in HTML) as described in RFC 3066 ([RFC3066]). For lang (or + xml:lang) language subcode matching, please see the :lang pseudo-class.
+
+ +

Attribute values must be identifiers or strings. The +case-sensitivity of attribute names and values in selectors depends on +the document language.

+ +
+ +

Examples:

+ +

The following attribute selector represents an h1 + element that carries the title attribute, whatever its + value:

+ +
h1[title]
+ +

In the following example, the selector represents a + span element whose class attribute has + exactly the value "example":

+ +
span[class="example"]
+ +

Multiple attribute selectors can be used to represent several + attributes of an element, or several conditions on the same + attribute. Here, the selector represents a span element + whose hello attribute has exactly the value "Cleveland" + and whose goodbye attribute has exactly the value + "Columbus":

+ +
span[hello="Cleveland"][goodbye="Columbus"]
+ +

The following selectors illustrate the differences between "=" + and "~=". The first selector will represent, for example, the value + "copyright copyleft copyeditor" on a rel attribute. The + second selector will only represent an a element with + an href attribute having the exact value + "http://www.w3.org/".

+ +
a[rel~="copyright"]
+a[href="http://www.w3.org/"]
+ +

The following selector represents a link element + whose hreflang attribute is exactly "fr".

+ +
link[hreflang=fr]
+ +

The following selector represents a link element for + which the values of the hreflang attribute begins with + "en", including "en", "en-US", and "en-cockney":

+ +
link[hreflang|="en"]
+ +

Similarly, the following selectors represents a + DIALOGUE element whenever it has one of two different + values for an attribute character:

+ +
DIALOGUE[character=romeo]
+DIALOGUE[character=juliet]
+ +
+ +

6.3.2. Substring matching attribute +selectors

+ +

Three additional attribute selectors are provided for matching +substrings in the value of an attribute:

+ +
+
[att^=val]
+
Represents an element with the att attribute whose value begins + with the prefix "val".
+
[att$=val] +
Represents an element with the att attribute whose value ends with + the suffix "val".
+
[att*=val] +
Represents an element with the att attribute whose value contains + at least one instance of the substring "val".
+
+ +

Attribute values must be identifiers or strings. The +case-sensitivity of attribute names in selectors depends on the +document language.

+ +
+

Examples:

+

The following selector represents an HTML object, referencing an + image:

+
object[type^="image/"]
+

The following selector represents an HTML anchor a with an + href attribute whose value ends with ".html".

+
a[href$=".html"]
+

The following selector represents an HTML paragraph with a title + attribute whose value contains the substring "hello"

+
p[title*="hello"]
+
+ +

6.3.3. Attribute selectors and namespaces

+ +

Attribute selectors allow an optional namespace component to the +attribute name. A namespace prefix that has been previously declared +may be prepended to the attribute name separated by the namespace +separator "vertical bar" (|). In keeping with +the Namespaces in the XML recommendation, default namespaces do not +apply to attributes, therefore attribute selectors without a namespace +component apply only to attributes that have no declared namespace +(equivalent to "|attr"). An asterisk may be used for the +namespace prefix indicating that the selector is to match all +attribute names without regard to the attribute's namespace. + +

An attribute selector with an attribute name containing a namespace +prefix that has not been previously declared is an invalid selector. The mechanism for declaring +a namespace prefix is left up to the language implementing Selectors. +In CSS, such a mechanism is defined in the General Syntax module. + +

+

CSS examples:

+
@namespace foo "http://www.example.com";
+[foo|att=val] { color: blue }
+[*|att] { color: yellow }
+[|att] { color: green }
+[att] { color: green }
+ +

The first rule will match only elements with the attribute + att in the "http://www.example.com" namespace with the + value "val".

+ +

The second rule will match only elements with the attribute + att regardless of the namespace of the attribute + (including no declared namespace).

+ +

The last two rules are equivalent and will match only elements + with the attribute att where the attribute is not + declared to be in a namespace.

+ +
+ +

6.3.4. Default attribute values in DTDs

+ +

Attribute selectors represent explicitly set attribute values in +the document tree. Default attribute values may be defined in a DTD or +elsewhere, but cannot always be selected by attribute +selectors. Selectors should be designed so that they work even if the +default values are not included in the document tree.

+ +

More precisely, a UA is not required to read an "external +subset" of the DTD but is required to look for default +attribute values in the document's "internal subset." (See [XML10] for definitions of these subsets.)

+ +

A UA that recognizes an XML namespace [XMLNAMES] is not required to use its +knowledge of that namespace to treat default attribute values as if +they were present in the document. (For example, an XHTML UA is not +required to use its built-in knowledge of the XHTML DTD.)

+ +

Note: Typically, implementations +choose to ignore external subsets.

+ +
+

Example:

+ +

Consider an element EXAMPLE with an attribute "notation" that has a +default value of "decimal". The DTD fragment might be

+ +
<!ATTLIST EXAMPLE notation (decimal,octal) "decimal">
+ +

If the style sheet contains the rules

+ +
EXAMPLE[notation=decimal] { /*... default property settings ...*/ }
+EXAMPLE[notation=octal]   { /*... other settings...*/ }
+ +

the first rule will not match elements whose "notation" attribute +is set by default, i.e. not set explicitly. To catch all cases, the +attribute selector for the default value must be dropped:

+ +
EXAMPLE                   { /*... default property settings ...*/ }
+EXAMPLE[notation=octal]   { /*... other settings...*/ }
+ +

Here, because the selector EXAMPLE[notation=octal] is +more specific than the tag +selector alone, the style declarations in the second rule will override +those in the first for elements that have a "notation" attribute value +of "octal". Care has to be taken that all property declarations that +are to apply only to the default case are overridden in the non-default +cases' style rules.

+ +
+ +

6.4. Class selectors

+ +

Working with HTML, authors may use the period (U+002E, +.) notation as an alternative to the ~= +notation when representing the class attribute. Thus, for +HTML, div.value and div[class~=value] have +the same meaning. The attribute value must immediately follow the +"period" (.).

+ +

UAs may apply selectors using the period (.) notation in XML +documents if the UA has namespace-specific knowledge that allows it to +determine which attribute is the "class" attribute for the +respective namespace. One such example of namespace-specific knowledge +is the prose in the specification for a particular namespace (e.g. SVG +1.0 [SVG] describes the SVG +"class" attribute and how a UA should interpret it, and +similarly MathML 1.01 [MATH] describes the MathML +"class" attribute.)

+ +
+

CSS examples:

+ +

We can assign style information to all elements with + class~="pastoral" as follows:

+ +
*.pastoral { color: green }  /* all elements with class~=pastoral */
+ +

or just

+ +
.pastoral { color: green }  /* all elements with class~=pastoral */
+ +

The following assigns style only to H1 elements with + class~="pastoral":

+ +
H1.pastoral { color: green }  /* H1 elements with class~=pastoral */
+ +

Given these rules, the first H1 instance below would not have + green text, while the second would:

+ +
<H1>Not green</H1>
+<H1 class="pastoral">Very green</H1>
+ +
+ +

To represent a subset of "class" values, each value must be preceded +by a ".", in any order.

+ +
+ +

CSS example:

+ +

The following rule matches any P element whose "class" attribute + has been assigned a list of whitespace-separated values that includes + "pastoral" and "marine":

+ +
p.pastoral.marine { color: green }
+ +

This rule matches when class="pastoral blue aqua + marine" but does not match for class="pastoral + blue".

+ +
+ +

Note: Because CSS gives considerable +power to the "class" attribute, authors could conceivably design their +own "document language" based on elements with almost no associated +presentation (such as DIV and SPAN in HTML) and assigning style +information through the "class" attribute. Authors should avoid this +practice since the structural elements of a document language often +have recognized and accepted meanings and author-defined classes may +not.

+ +

Note: If an element has multiple +class attributes, their values must be concatenated with spaces +between the values before searching for the class. As of this time the +working group is not aware of any manner in which this situation can +be reached, however, so this behavior is explicitly non-normative in +this specification.

+ +

6.5. ID selectors

+ +

Document languages may contain attributes that are declared to be +of type ID. What makes attributes of type ID special is that no two +such attributes can have the same value in a document, regardless of +the type of the elements that carry them; whatever the document +language, an ID typed attribute can be used to uniquely identify its +element. In HTML all ID attributes are named "id"; XML applications +may name ID attributes differently, but the same restriction +applies.

+ +

An ID-typed attribute of a document language allows authors to +assign an identifier to one element instance in the document tree. W3C +ID selectors represent an element instance based on its identifier. An +ID selector contains a "number sign" (U+0023, +#) immediately followed by the ID value, which must be an +identifier.

+ +

Selectors does not specify how a UA knows the ID-typed attribute of +an element. The UA may, e.g., read a document's DTD, have the +information hard-coded or ask the user. + +

+

Examples:

+

The following ID selector represents an h1 element + whose ID-typed attribute has the value "chapter1":

+
h1#chapter1
+

The following ID selector represents any element whose ID-typed + attribute has the value "chapter1":

+
#chapter1
+

The following selector represents any element whose ID-typed + attribute has the value "z98y".

+
*#z98y
+
+ +

Note. In XML 1.0 [XML10], the information about which attribute +contains an element's IDs is contained in a DTD or a schema. When +parsing XML, UAs do not always read the DTD, and thus may not know +what the ID of an element is (though a UA may have namespace-specific +knowledge that allows it to determine which attribute is the ID +attribute for that namespace). If a style sheet designer knows or +suspects that a UA may not know what the ID of an element is, he +should use normal attribute selectors instead: +[name=p371] instead of #p371. Elements in +XML 1.0 documents without a DTD do not have IDs at all.

+ +

If an element has multiple ID attributes, all of them must be +treated as IDs for that element for the purposes of the ID +selector. Such a situation could be reached using mixtures of xml:id, +DOM3 Core, XML DTDs, and namespace-specific knowledge.

+ +

6.6. Pseudo-classes

+ +

The pseudo-class concept is introduced to permit selection based on +information that lies outside of the document tree or that cannot be +expressed using the other simple selectors.

+ +

A pseudo-class always consists of a "colon" +(:) followed by the name of the pseudo-class and +optionally by a value between parentheses.

+ +

Pseudo-classes are allowed in all sequences of simple selectors +contained in a selector. Pseudo-classes are allowed anywhere in +sequences of simple selectors, after the leading type selector or +universal selector (possibly omitted). Pseudo-class names are +case-insensitive. Some pseudo-classes are mutually exclusive, while +others can be applied simultaneously to the same +element. Pseudo-classes may be dynamic, in the sense that an element +may acquire or lose a pseudo-class while a user interacts with the +document.

+ + +

6.6.1. Dynamic pseudo-classes

+ +

Dynamic pseudo-classes classify elements on characteristics other +than their name, attributes, or content, in principle characteristics +that cannot be deduced from the document tree.

+ +

Dynamic pseudo-classes do not appear in the document source or +document tree.

+ + +
The link pseudo-classes: :link and :visited
+ +

User agents commonly display unvisited links differently from +previously visited ones. Selectors +provides the pseudo-classes :link and +:visited to distinguish them:

+ + + +

After some amount of time, user agents may choose to return a +visited link to the (unvisited) ':link' state.

+ +

The two states are mutually exclusive.

+ +
+ +

Example:

+ +

The following selector represents links carrying class + external and already visited:

+ +
a.external:visited
+ +
+ +

Note: It is possible for style sheet +authors to abuse the :link and :visited pseudo-classes to determine +which sites a user has visited without the user's consent. + +

UAs may therefore treat all links as unvisited links, or implement +other measures to preserve the user's privacy while rendering visited +and unvisited links differently.

+ +
The user action pseudo-classes +:hover, :active, and :focus
+ +

Interactive user agents sometimes change the rendering in response +to user actions. Selectors provides +three pseudo-classes for the selection of an element the user is +acting on.

+ + + +

There may be document language or implementation specific limits on +which elements can become :active or acquire +:focus.

+ +

These pseudo-classes are not mutually exclusive. An element may +match several pseudo-classes at the same time.

+ +

Selectors doesn't define if the parent of an element that is +':active' or ':hover' is also in that state.

+ +
+

Examples:

+
a:link    /* unvisited links */
+a:visited /* visited links */
+a:hover   /* user hovers */
+a:active  /* active links */
+

An example of combining dynamic pseudo-classes:

+
a:focus
+a:focus:hover
+

The last selector matches a elements that are in + the pseudo-class :focus and in the pseudo-class :hover.

+
+ +

Note: An element can be both ':visited' +and ':active' (or ':link' and ':active').

+ +

6.6.2. The target pseudo-class :target

+ +

Some URIs refer to a location within a resource. This kind of URI +ends with a "number sign" (#) followed by an anchor +identifier (called the fragment identifier).

+ +

URIs with fragment identifiers link to a certain element within the +document, known as the target element. For instance, here is a URI +pointing to an anchor named section_2 in an HTML +document:

+ +
http://example.com/html/top.html#section_2
+ +

A target element can be represented by the :target +pseudo-class. If the document's URI has no fragment identifier, then +the document has no target element.

+ +
+

Example:

+
p.note:target
+

This selector represents a p element of class + note that is the target element of the referring + URI.

+
+ +
+

CSS example:

+

Here, the :target pseudo-class is used to make the + target element red and place an image before it, if there is one:

+
*:target { color : red }
+*:target::before { content : url(target.png) }
+
+ +

6.6.3. The language pseudo-class :lang

+ +

If the document language specifies how the human language of an +element is determined, it is possible to write selectors that +represent an element based on its language. For example, in HTML [HTML4], the language is determined by a +combination of the lang attribute, the meta +element, and possibly by information from the protocol (such as HTTP +headers). XML uses an attribute called xml:lang, and +there may be other document language-specific methods for determining +the language.

+ +

The pseudo-class :lang(C) represents an element that +is in language C. Whether an element is represented by a +:lang() selector is based solely on the identifier C +being either equal to, or a hyphen-separated substring of, the +element's language value, in the same way as if performed by the '|=' operator in attribute +selectors. The identifier C does not have to be a valid language +name.

+ +

C must not be empty. (If it is, the selector is invalid.)

+ +

Note: It is recommended that +documents and protocols indicate language using codes from RFC 3066 [RFC3066] or its successor, and by means of +"xml:lang" attributes in the case of XML-based documents [XML10]. See +"FAQ: Two-letter or three-letter language codes."

+ +
+

Examples:

+

The two following selectors represent an HTML document that is in + Belgian, French, or German. The two next selectors represent + q quotations in an arbitrary element in Belgian, French, + or German.

+
html:lang(fr-be)
+html:lang(de)
+:lang(fr-be) > q
+:lang(de) > q
+
+ +

6.6.4. The UI element states pseudo-classes

+ +
The :enabled and :disabled pseudo-classes
+ +

The :enabled pseudo-class allows authors to customize +the look of user interface elements that are enabled — which the +user can select or activate in some fashion (e.g. clicking on a button +with a mouse). There is a need for such a pseudo-class because there +is no way to programmatically specify the default appearance of say, +an enabled input element without also specifying what it +would look like when it was disabled.

+ +

Similar to :enabled, :disabled allows the +author to specify precisely how a disabled or inactive user interface +element should look.

+ +

Most elements will be neither enabled nor disabled. An element is +enabled if the user can either activate it or transfer the focus to +it. An element is disabled if it could be enabled, but the user cannot +presently activate it or transfer focus to it.

+ + +
The :checked pseudo-class
+ +

Radio and checkbox elements can be toggled by the user. Some menu +items are "checked" when the user selects them. When such elements are +toggled "on" the :checked pseudo-class applies. The +:checked pseudo-class initially applies to such elements +that have the HTML4 selected and checked +attributes as described in Section +17.2.1 of HTML4, but of course the user can toggle "off" such +elements in which case the :checked pseudo-class would no +longer apply. While the :checked pseudo-class is dynamic +in nature, and is altered by user action, since it can also be based +on the presence of the semantic HTML4 selected and +checked attributes, it applies to all media. + + +

The :indeterminate pseudo-class
+ +
+ +

Radio and checkbox elements can be toggled by the user, but are +sometimes in an indeterminate state, neither checked nor unchecked. +This can be due to an element attribute, or DOM manipulation.

+ +

A future version of this specification may introduce an +:indeterminate pseudo-class that applies to such elements. +

+ +
+ + +

6.6.5. Structural pseudo-classes

+ +

Selectors introduces the concept of structural +pseudo-classes to permit selection based on extra information that lies in +the document tree but cannot be represented by other simple selectors or +combinators. + +

Note that standalone pieces of PCDATA (text nodes in the DOM) are +not counted when calculating the position of an element in the list of +children of its parent. When calculating the position of an element in +the list of children of its parent, the index numbering starts at 1. + + +

:root pseudo-class
+ +

The :root pseudo-class represents an element that is +the root of the document. In HTML 4, this is always the +HTML element. + + +

:nth-child() pseudo-class
+ +

The +:nth-child(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings +before it in the document tree, for a given positive +integer or zero value of n, and has a parent element. In +other words, this matches the bth child of an element after +all the children have been split into groups of a elements +each. For example, this allows the selectors to address every other +row in a table, and could be used to alternate the color +of paragraph text in a cycle of four. The a and +b values must be zero, negative integers or positive +integers. The index of the first child of an element is 1. + +

In addition to this, :nth-child() can take +'odd' and 'even' as arguments instead. +'odd' has the same signification as 2n+1, +and 'even' has the same signification as 2n. + + +

+

Examples:

+
tr:nth-child(2n+1) /* represents every odd row of an HTML table */
+tr:nth-child(odd)  /* same */
+tr:nth-child(2n)   /* represents every even row of an HTML table */
+tr:nth-child(even) /* same */
+
+/* Alternate paragraph colours in CSS */
+p:nth-child(4n+1) { color: navy; }
+p:nth-child(4n+2) { color: green; }
+p:nth-child(4n+3) { color: maroon; }
+p:nth-child(4n+4) { color: purple; }
+
+ +

When a=0, no repeating is used, so for example +:nth-child(0n+5) matches only the fifth child. When +a=0, the an part need not be +included, so the syntax simplifies to +:nth-child(b) and the last example simplifies +to :nth-child(5). + +

+

Examples:

+
foo:nth-child(0n+1)   /* represents an element foo, first child of its parent element */
+foo:nth-child(1)      /* same */
+
+ +

When a=1, the number may be omitted from the rule. + +

+

Examples:

+

The following selectors are therefore equivalent:

+
bar:nth-child(1n+0)   /* represents all bar elements, specificity (0,1,1) */
+bar:nth-child(n+0)    /* same */
+bar:nth-child(n)      /* same */
+bar                   /* same but lower specificity (0,0,1) */
+
+ +

If b=0, then every ath element is picked. In +such a case, the b part may be omitted. + +

+

Examples:

+
tr:nth-child(2n+0) /* represents every even row of an HTML table */
+tr:nth-child(2n) /* same */
+
+ +

If both a and b are equal to zero, the +pseudo-class represents no element in the document tree.

+ +

The value a can be negative, but only the positive +values of an+b, for +n≥0, may represent an element in the document +tree.

+ +
+

Example:

+
html|tr:nth-child(-n+6)  /* represents the 6 first rows of XHTML tables */
+
+ +

When the value b is negative, the "+" character in the +expression must be removed (it is effectively replaced by the "-" +character indicating the negative value of b).

+ +
+

Examples:

+
:nth-child(10n-1)  /* represents the 9th, 19th, 29th, etc, element */
+:nth-child(10n+9)  /* Same */
+:nth-child(10n+-1) /* Syntactically invalid, and would be ignored */
+
+ + +
:nth-last-child() pseudo-class
+ +

The :nth-last-child(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings +after it in the document tree, for a given positive +integer or zero value of n, and has a parent element. See +:nth-child() pseudo-class for the syntax of its argument. +It also accepts the 'even' and 'odd' values +as arguments. + + +

+

Examples:

+
tr:nth-last-child(-n+2)    /* represents the two last rows of an HTML table */
+
+foo:nth-last-child(odd)    /* represents all odd foo elements in their parent element,
+                              counting from the last one */
+
+ + +
:nth-of-type() pseudo-class
+ +

The :nth-of-type(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings with the same +element name before it in the document tree, for a +given zero or positive integer value of n, and has a +parent element. In other words, this matches the bth child +of that type after all the children of that type have been split into +groups of a elements each. See :nth-child() pseudo-class +for the syntax of its argument. It also accepts the +'even' and 'odd' values. + + +

+

CSS example:

+

This allows an author to alternate the position of floated images:

+
img:nth-of-type(2n+1) { float: right; }
+img:nth-of-type(2n) { float: left; }
+
+ + +
:nth-last-of-type() pseudo-class
+ +

The :nth-last-of-type(an+b) +pseudo-class notation represents an element that has +an+b-1 siblings with the same +element name after it in the document tree, for a +given zero or positive integer value of n, and has a +parent element. See :nth-child() pseudo-class for the +syntax of its argument. It also accepts the 'even' and 'odd' values. + + +

+

Example:

+

To represent all h2 children of an XHTML + body except the first and last, one could use the + following selector:

+
body > h2:nth-of-type(n+2):nth-last-of-type(n+2)
+

In this case, one could also use :not(), although the + selector ends up being just as long:

+
body > h2:not(:first-of-type):not(:last-of-type)
+
+ + +
:first-child pseudo-class
+ +

Same as :nth-child(1). The :first-child pseudo-class +represents an element that is the first child of some other element. + + +

+

Examples:

+

The following selector represents a p element that is + the first child of a div element:

+
div > p:first-child
+

This selector can represent the p inside the + div of the following fragment:

+
<p> The last P before the note.</p>
+<div class="note">
+   <p> The first P inside the note.</p>
+</div>
but cannot represent the second p in the following +fragment: +
<p> The last P before the note.</p>
+<div class="note">
+   <h2> Note </h2>
+   <p> The first P inside the note.</p>
+</div>
+

The following two selectors are usually equivalent:

+
* > a:first-child /* a is first child of any element */
+a:first-child /* Same (assuming a is not the root element) */
+
+ +
:last-child pseudo-class
+ +

Same as :nth-last-child(1). The :last-child pseudo-class +represents an element that is the last child of some other element. + +

+

Example:

+

The following selector represents a list item li that + is the last child of an ordered list ol. +

ol > li:last-child
+
+ +
:first-of-type pseudo-class
+ +

Same as :nth-of-type(1). The :first-of-type pseudo-class +represents an element that is the first sibling of its type in the list of +children of its parent element. + +

+

Example:

+

The following selector represents a definition title +dt inside a definition list dl, this +dt being the first of its type in the list of children of +its parent element.

+
dl dt:first-of-type
+

It is a valid description for the first two dt +elements in the following example but not for the third one:

+
<dl>
+ <dt>gigogne</dt>
+ <dd>
+  <dl>
+   <dt>fusée</dt>
+   <dd>multistage rocket</dd>
+   <dt>table</dt>
+   <dd>nest of tables</dd>
+  </dl>
+ </dd>
+</dl>
+
+ +
:last-of-type pseudo-class
+ +

Same as :nth-last-of-type(1). The +:last-of-type pseudo-class represents an element that is +the last sibling of its type in the list of children of its parent +element.

+ +
+

Example:

+

The following selector represents the last data cell + td of a table row.

+
tr > td:last-of-type
+
+ +
:only-child pseudo-class
+ +

Represents an element that has a parent element and whose parent +element has no other element children. Same as +:first-child:last-child or +:nth-child(1):nth-last-child(1), but with a lower +specificity.

+ +
:only-of-type pseudo-class
+ +

Represents an element that has a parent element and whose parent +element has no other element children with the same element name. Same +as :first-of-type:last-of-type or +:nth-of-type(1):nth-last-of-type(1), but with a lower +specificity.

+ + +
:empty pseudo-class
+ +

The :empty pseudo-class represents an element that has +no children at all. In terms of the DOM, only element nodes and text +nodes (including CDATA nodes and entity references) whose data has a +non-zero length must be considered as affecting emptiness; comments, +PIs, and other nodes must not affect whether an element is considered +empty or not.

+ +
+

Examples:

+

p:empty is a valid representation of the following fragment:

+
<p></p>
+

foo:empty is not a valid representation for the + following fragments:

+
<foo>bar</foo>
+
<foo><bar>bla</bar></foo>
+
<foo>this is not <bar>:empty</bar></foo>
+
+ +

6.6.6. Blank

+ +

This section intentionally left blank.

+ + +

6.6.7. The negation pseudo-class

+ +

The negation pseudo-class, :not(X), is a +functional notation taking a simple +selector (excluding the negation pseudo-class itself and +pseudo-elements) as an argument. It represents an element that is not +represented by the argument. + + + +

+

Examples:

+

The following CSS selector matches all button + elements in an HTML document that are not disabled.

+
button:not([DISABLED])
+

The following selector represents all but FOO + elements.

+
*:not(FOO)
+

The following group of selectors represents all HTML elements + except links.

+
html|*:not(:link):not(:visited)
+
+ +

Default namespace declarations do not affect the argument of the +negation pseudo-class unless the argument is a universal selector or a +type selector.

+ +
+

Examples:

+

Assuming that the default namespace is bound to + "http://example.com/", the following selector represents all + elements that are not in that namespace:

+
*|*:not(*)
+

The following CSS selector matches any element being hovered, + regardless of its namespace. In particular, it is not limited to + only matching elements in the default namespace that are not being + hovered, and elements not in the default namespace don't match the + rule when they are being hovered.

+
*|*:not(:hover)
+
+ +

Note: the :not() pseudo allows +useless selectors to be written. For instance :not(*|*), +which represents no element at all, or foo:not(bar), +which is equivalent to foo but with a higher +specificity.

+ +

7. Pseudo-elements

+ +

Pseudo-elements create abstractions about the document tree beyond +those specified by the document language. For instance, document +languages do not offer mechanisms to access the first letter or first +line of an element's content. Pseudo-elements allow designers to refer +to this otherwise inaccessible information. Pseudo-elements may also +provide designers a way to refer to content that does not exist in the +source document (e.g., the ::before and +::after pseudo-elements give access to generated +content).

+ +

A pseudo-element is made of two colons (::) followed +by the name of the pseudo-element.

+ +

This :: notation is introduced by the current document +in order to establish a discrimination between pseudo-classes and +pseudo-elements. For compatibility with existing style sheets, user +agents must also accept the previous one-colon notation for +pseudo-elements introduced in CSS levels 1 and 2 (namely, +:first-line, :first-letter, +:before and :after). This compatibility is +not allowed for the new pseudo-elements introduced in CSS level 3.

+ +

Only one pseudo-element may appear per selector, and if present it +must appear after the sequence of simple selectors that represents the +subjects of the selector. A +future version of this specification may allow multiple +pesudo-elements per selector.

+ +

7.1. The ::first-line pseudo-element

+ +

The ::first-line pseudo-element describes the contents +of the first formatted line of an element. + +

+

CSS example:

+
p::first-line { text-transform: uppercase }
+

The above rule means "change the letters of the first line of every +paragraph to uppercase".

+
+ +

The selector p::first-line does not match any real +HTML element. It does match a pseudo-element that conforming user +agents will insert at the beginning of every paragraph.

+ +

Note that the length of the first line depends on a number of +factors, including the width of the page, the font size, etc. Thus, +an ordinary HTML paragraph such as:

+ +
+<P>This is a somewhat long HTML 
+paragraph that will be broken into several 
+lines. The first line will be identified
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

the lines of which happen to be broken as follows: + +

+THIS IS A SOMEWHAT LONG HTML PARAGRAPH THAT
+will be broken into several lines. The first
+line will be identified by a fictional tag 
+sequence. The other lines will be treated as 
+ordinary lines in the paragraph.
+
+ +

This paragraph might be "rewritten" by user agents to include the +fictional tag sequence for ::first-line. This +fictional tag sequence helps to show how properties are inherited.

+ +
+<P><P::first-line> This is a somewhat long HTML 
+paragraph that </P::first-line> will be broken into several
+lines. The first line will be identified 
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

If a pseudo-element breaks up a real element, the desired effect +can often be described by a fictional tag sequence that closes and +then re-opens the element. Thus, if we mark up the previous paragraph +with a span element:

+ +
+<P><SPAN class="test"> This is a somewhat long HTML
+paragraph that will be broken into several
+lines.</SPAN> The first line will be identified
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

the user agent could simulate start and end tags for +span when inserting the fictional tag sequence for +::first-line. + +

+<P><P::first-line><SPAN class="test"> This is a
+somewhat long HTML
+paragraph that will </SPAN></P::first-line><SPAN class="test"> be
+broken into several
+lines.</SPAN> The first line will be identified
+by a fictional tag sequence. The other lines
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

In CSS, the ::first-line pseudo-element can only be +attached to a block-level element, an inline-block, a table-caption, +or a table-cell.

+ +

The "first formatted line" of an +element may occur inside a +block-level descendant in the same flow (i.e., a block-level +descendant that is not positioned and not a float). E.g., the first +line of the div in <DIV><P>This +line...</P></DIV> is the first line of the p (assuming +that both p and div are block-level). + +

The first line of a table-cell or inline-block cannot be the first +formatted line of an ancestor element. Thus, in <DIV><P +STYLE="display: inline-block">Hello<BR>Goodbye</P> +etcetera</DIV> the first formatted line of the +div is not the line "Hello". + +

Note that the first line of the p in this +fragment: <p><br>First... doesn't contain any +letters (assuming the default style for br in HTML +4). The word "First" is not on the first formatted line. + +

A UA should act as if the fictional start tags of the +::first-line pseudo-elements were nested just inside the +innermost enclosing block-level element. (Since CSS1 and CSS2 were +silent on this case, authors should not rely on this behavior.) Here +is an example. The fictional tag sequence for

+ +
+<DIV>
+  <P>First paragraph</P>
+  <P>Second paragraph</P>
+</DIV>
+
+ +

is

+ +
+<DIV>
+  <P><DIV::first-line><P::first-line>First paragraph</P::first-line></DIV::first-line></P>
+  <P><P::first-line>Second paragraph</P::first-line></P>
+</DIV>
+
+ +

The ::first-line pseudo-element is similar to an +inline-level element, but with certain restrictions. In CSS, the +following properties apply to a ::first-line +pseudo-element: font properties, color property, background +properties, 'word-spacing', 'letter-spacing', 'text-decoration', +'vertical-align', 'text-transform', 'line-height'. UAs may apply other +properties as well.

+ + +

7.2. The ::first-letter pseudo-element

+ +

The ::first-letter pseudo-element represents the first +letter of the first line of a block, if it is not preceded by any +other content (such as images or inline tables) on its line. The +::first-letter pseudo-element may be used for "initial caps" and "drop +caps", which are common typographical effects. This type of initial +letter is similar to an inline-level element if its 'float' property +is 'none'; otherwise, it is similar to a floated element.

+ +

In CSS, these are the properties that apply to ::first-letter +pseudo-elements: font properties, 'text-decoration', 'text-transform', +'letter-spacing', 'word-spacing' (when appropriate), 'line-height', +'float', 'vertical-align' (only if 'float' is 'none'), margin +properties, padding properties, border properties, color property, +background properties. UAs may apply other properties as well. To +allow UAs to render a typographically correct drop cap or initial cap, +the UA may choose a line-height, width and height based on the shape +of the letter, unlike for normal elements.

+ +
+

Example:

+

This example shows a possible rendering of an initial cap. Note +that the 'line-height' that is inherited by the ::first-letter +pseudo-element is 1.1, but the UA in this example has computed the +height of the first letter differently, so that it doesn't cause any +unnecessary space between the first two lines. Also note that the +fictional start tag of the first letter is inside the span, and thus +the font weight of the first letter is normal, not bold as the span: +

+p { line-height: 1.1 }
+p::first-letter { font-size: 3em; font-weight: normal }
+span { font-weight: bold }
+...
+<p><span>Het hemelsche</span> gerecht heeft zich ten lange lesten<br>
+Erbarremt over my en mijn benaeuwde vesten<br>
+En arme burgery, en op mijn volcx gebed<br>
+En dagelix geschrey de bange stad ontzet.
+
+
+

Image illustrating the ::first-letter pseudo-element +

+
+ +
+

The following CSS will make a drop cap initial letter span about two lines:

+ +
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<HTML>
+ <HEAD>
+  <TITLE>Drop cap initial letter</TITLE>
+  <STYLE type="text/css">
+   P               { font-size: 12pt; line-height: 1.2 }
+   P::first-letter { font-size: 200%; font-weight: bold; float: left }
+   SPAN            { text-transform: uppercase }
+  </STYLE>
+ </HEAD>
+ <BODY>
+  <P><SPAN>The first</SPAN> few words of an article
+    in The Economist.</P>
+ </BODY>
+</HTML>
+
+ +

This example might be formatted as follows:

+ +
+

Image illustrating the combined effect of the ::first-letter and ::first-line pseudo-elements

+
+ +

The fictional tag sequence is:

+ +
+<P>
+<SPAN>
+<P::first-letter>
+T
+</P::first-letter>he first
+</SPAN> 
+few words of an article in the Economist.
+</P>
+
+ +

Note that the ::first-letter pseudo-element tags abut +the content (i.e., the initial character), while the ::first-line +pseudo-element start tag is inserted right after the start tag of the +block element.

+ +

In order to achieve traditional drop caps formatting, user agents +may approximate font sizes, for example to align baselines. Also, the +glyph outline may be taken into account when formatting.

+ +

Punctuation (i.e, characters defined in Unicode in the "open" (Ps), +"close" (Pe), "initial" (Pi). "final" (Pf) and "other" (Po) +punctuation classes), that precedes or follows the first letter should +be included. [UNICODE]

+ +
+

Quotes that precede the
+first letter should be included.

+
+ +

The ::first-letter also applies if the first letter is +in fact a digit, e.g., the "6" in "67 million dollars is a lot of +money."

+ +

In CSS, the ::first-letter pseudo-element applies to +block, list-item, table-cell, table-caption, and inline-block +elements. A future version of this specification +may allow this pesudo-element to apply to more element +types.

+ +

The ::first-letter pseudo-element can be used with all +such elements that contain text, or that have a descendant in the same +flow that contains text. A UA should act as if the fictional start tag +of the ::first-letter pseudo-element is just before the first text of +the element, even if that first text is in a descendant.

+ +
+

Example:

+

The fictional tag sequence for this HTMLfragment: +

<div>
+<p>The first text.
+

is: +

<div>
+<p><div::first-letter><p::first-letter>T</...></...>he first text.
+
+ +

The first letter of a table-cell or inline-block cannot be the +first letter of an ancestor element. Thus, in <DIV><P +STYLE="display: inline-block">Hello<BR>Goodbye</P> +etcetera</DIV> the first letter of the div is not the +letter "H". In fact, the div doesn't have a first letter. + +

The first letter must occur on the first formatted line. For example, in +this fragment: <p><br>First... the first line +doesn't contain any letters and ::first-letter doesn't +match anything (assuming the default style for br in HTML +4). In particular, it does not match the "F" of "First." + +

In CSS, if an element is a list item ('display: list-item'), the +::first-letter applies to the first letter in the +principal box after the marker. UAs may ignore +::first-letter on list items with 'list-style-position: +inside'. If an element has ::before or +::after content, the ::first-letter applies +to the first letter of the element including that content. + +

+

Example:

+

After the rule 'p::before {content: "Note: "}', the selector +'p::first-letter' matches the "N" of "Note".

+
+ +

Some languages may have specific rules about how to treat certain +letter combinations. In Dutch, for example, if the letter combination +"ij" appears at the beginning of a word, both letters should be +considered within the ::first-letter pseudo-element. + +

If the letters that would form the ::first-letter are not in the +same element, such as "'T" in <p>'<em>T..., the UA +may create a ::first-letter pseudo-element from one of the elements, +both elements, or simply not create a pseudo-element.

+ +

Similarly, if the first letter(s) of the block are not at the start +of the line (for example due to bidirectional reordering), then the UA +need not create the pseudo-element(s). + +

+

Example:

+

The following example illustrates +how overlapping pseudo-elements may interact. The first letter of +each P element will be green with a font size of '24pt'. The rest of +the first formatted line will be 'blue' while the rest of the +paragraph will be 'red'.

+ +
p { color: red; font-size: 12pt }
+p::first-letter { color: green; font-size: 200% }
+p::first-line { color: blue }
+
+<P>Some text that ends up on two lines</P>
+ +

Assuming that a line break will occur before the word "ends", the +fictional tag +sequence for this fragment might be:

+ +
<P>
+<P::first-line>
+<P::first-letter> 
+S 
+</P::first-letter>ome text that 
+</P::first-line> 
+ends up on two lines 
+</P>
+ +

Note that the ::first-letter element is inside the ::first-line +element. Properties set on ::first-line are inherited by +::first-letter, but are overridden if the same property is set on +::first-letter.

+
+ + +

7.3. The ::selection pseudo-element

+ +

The ::selection pseudo-element applies to the portion +of a document that has been highlighted by the user. This also +applies, for example, to selected text within an editable text +field. This pseudo-element should not be confused with the :checked pseudo-class (which used to be +named :selected) + +

Although the ::selection pseudo-element is dynamic in +nature, and is altered by user action, it is reasonable to expect that +when a UA re-renders to a static medium (such as a printed page, see +[CSS21]) which was originally rendered to a +dynamic medium (like screen), the UA may wish to transfer the current +::selection state to that other medium, and have all the +appropriate formatting and rendering take effect as well. This is not +required — UAs may omit the ::selection +pseudo-element for static media. + +

These are the CSS properties that apply to ::selection +pseudo-elements: color, background, cursor (optional), outline +(optional). The computed value of the 'background-image' property on +::selection may be ignored. + + +

7.4. The ::before and ::after pseudo-elements

+ +

The ::before and ::after pseudo-elements +can be used to describe generated content before or after an element's +content. They are explained in CSS 2.1 [CSS21].

+ +

When the ::first-letter and ::first-line +pseudo-elements are combined with ::before and +::after, they apply to the first letter or line of the +element including the inserted text.

+ +

8. Combinators

+ +

8.1. Descendant combinator

+ +

At times, authors may want selectors to describe an element that is +the descendant of another element in the document tree (e.g., "an +EM element that is contained within an H1 +element"). Descendant combinators express such a relationship. A +descendant combinator is white space that +separates two sequences of simple selectors. A selector of the form +"A B" represents an element B that is an +arbitrary descendant of some ancestor element A. + +

+

Examples:

+

For example, consider the following selector:

+
h1 em
+

It represents an em element being the descendant of + an h1 element. It is a correct and valid, but partial, + description of the following fragment:

+
<h1>This <span class="myclass">headline
+is <em>very</em> important</span></h1>
+

The following selector:

+
div * p
+

represents a p element that is a grandchild or later + descendant of a div element. Note the whitespace on + either side of the "*" is not part of the universal selector; the + whitespace is a combinator indicating that the DIV must be the + ancestor of some element, and that that element must be an ancestor + of the P.

+

The following selector, which combines descendant combinators and + attribute selectors, represents an + element that (1) has the href attribute set and (2) is + inside a p that is itself inside a div:

+
div p *[href]
+
+ +

8.2. Child combinators

+ +

A child combinator describes a childhood relationship +between two elements. A child combinator is made of the +"greater-than sign" (>) character and +separates two sequences of simple selectors. + + +

+

Examples:

+

The following selector represents a p element that is + child of body:

+
body > p
+

The following example combines descendant combinators and child + combinators.

+
div ol>li p
+

It represents a p element that is a descendant of an + li element; the li element must be the + child of an ol element; the ol element must + be a descendant of a div. Notice that the optional white + space around the ">" combinator has been left out.

+
+ +

For information on selecting the first child of an element, please +see the section on the :first-child pseudo-class +above.

+ +

8.3. Sibling combinators

+ +

There are two different sibling combinators: the adjacent sibling +combinator and the general sibling combinator. In both cases, +non-element nodes (e.g. text between elements) are ignored when +considering adjacency of elements.

+ +

8.3.1. Adjacent sibling combinator

+ +

The adjacent sibling combinator is made of the "plus +sign" (U+002B, +) character that separates two +sequences of simple selectors. The elements represented by the two +sequences share the same parent in the document tree and the element +represented by the first sequence immediately precedes the element +represented by the second one.

+ +
+

Examples:

+

The following selector represents a p element + immediately following a math element:

+
math + p
+

The following selector is conceptually similar to the one in the + previous example, except that it adds an attribute selector — it + adds a constraint to the h1 element, that it must have + class="opener":

+
h1.opener + h2
+
+ + +

8.3.2. General sibling combinator

+ +

The general sibling combinator is made of the "tilde" +(U+007E, ~) character that separates two sequences of +simple selectors. The elements represented by the two sequences share +the same parent in the document tree and the element represented by +the first sequence precedes (not necessarily immediately) the element +represented by the second one.

+ +
+

Example:

+
h1 ~ pre
+

represents a pre element following an h1. It + is a correct and valid, but partial, description of:

+
<h1>Definition of the function a</h1>
+<p>Function a(x) has to be applied to all figures in the table.</p>
+<pre>function a(x) = 12x/13.5</pre>
+
+ +

9. Calculating a selector's specificity

+ +

A selector's specificity is calculated as follows:

+ + + +

Selectors inside the negation pseudo-class +are counted like any other, but the negation itself does not count as +a pseudo-class.

+ +

Concatenating the three numbers a-b-c (in a number system with a +large base) gives the specificity.

+ +
+

Examples:

+
*               /* a=0 b=0 c=0 -> specificity =   0 */
+LI              /* a=0 b=0 c=1 -> specificity =   1 */
+UL LI           /* a=0 b=0 c=2 -> specificity =   2 */
+UL OL+LI        /* a=0 b=0 c=3 -> specificity =   3 */
+H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity =  11 */
+UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */
+LI.red.level    /* a=0 b=2 c=1 -> specificity =  21 */
+#x34y           /* a=1 b=0 c=0 -> specificity = 100 */
+#s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 101 */
+
+
+ +

Note: the specificity of the styles +specified in an HTML style attribute is described in CSS +2.1. [CSS21].

+ +

10. The grammar of Selectors

+ +

10.1. Grammar

+ +

The grammar below defines the syntax of Selectors. It is globally +LL(1) and can be locally LL(2) (but note that most UA's should not use +it directly, since it doesn't express the parsing conventions). The +format of the productions is optimized for human consumption and some +shorthand notations beyond Yacc (see [YACC]) +are used:

+ + + +

The productions are:

+ +
selectors_group
+  : selector [ COMMA S* selector ]*
+  ;
+
+selector
+  : simple_selector_sequence [ combinator simple_selector_sequence ]*
+  ;
+
+combinator
+  /* combinators can be surrounded by white space */
+  : PLUS S* | GREATER S* | TILDE S* | S+
+  ;
+
+simple_selector_sequence
+  : [ type_selector | universal ]
+    [ HASH | class | attrib | pseudo | negation ]*
+  | [ HASH | class | attrib | pseudo | negation ]+
+  ;
+
+type_selector
+  : [ namespace_prefix ]? element_name
+  ;
+
+namespace_prefix
+  : [ IDENT | '*' ]? '|'
+  ;
+
+element_name
+  : IDENT
+  ;
+
+universal
+  : [ namespace_prefix ]? '*'
+  ;
+
+class
+  : '.' IDENT
+  ;
+
+attrib
+  : '[' S* [ namespace_prefix ]? IDENT S*
+        [ [ PREFIXMATCH |
+            SUFFIXMATCH |
+            SUBSTRINGMATCH |
+            '=' |
+            INCLUDES |
+            DASHMATCH ] S* [ IDENT | STRING ] S*
+        ]? ']'
+  ;
+
+pseudo
+  /* '::' starts a pseudo-element, ':' a pseudo-class */
+  /* Exceptions: :first-line, :first-letter, :before and :after. */
+  /* Note that pseudo-elements are restricted to one per selector and */
+  /* occur only in the last simple_selector_sequence. */
+  : ':' ':'? [ IDENT | functional_pseudo ]
+  ;
+
+functional_pseudo
+  : FUNCTION S* expression ')'
+  ;
+
+expression
+  /* In CSS3, the expressions are identifiers, strings, */
+  /* or of the form "an+b" */
+  : [ [ PLUS | '-' | DIMENSION | NUMBER | STRING | IDENT ] S* ]+
+  ;
+
+negation
+  : NOT S* negation_arg S* ')'
+  ;
+
+negation_arg
+  : type_selector | universal | HASH | class | attrib | pseudo
+  ;
+ + +

10.2. Lexical scanner

+ +

The following is the tokenizer, written in Flex (see +[FLEX]) notation. The tokenizer is +case-insensitive.

+ +

The two occurrences of "\377" represent the highest character +number that current versions of Flex can deal with (decimal 255). They +should be read as "\4177777" (decimal 1114111), which is the highest +possible code point in Unicode/ISO-10646. [UNICODE]

+ +
%option case-insensitive
+
+ident     [-]?{nmstart}{nmchar}*
+name      {nmchar}+
+nmstart   [_a-z]|{nonascii}|{escape}
+nonascii  [^\0-\177]
+unicode   \\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?
+escape    {unicode}|\\[^\n\r\f0-9a-f]
+nmchar    [_a-z0-9-]|{nonascii}|{escape}
+num       [0-9]+|[0-9]*\.[0-9]+
+string    {string1}|{string2}
+string1   \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*\"
+string2   \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*\'
+invalid   {invalid1}|{invalid2}
+invalid1  \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*
+invalid2  \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*
+nl        \n|\r\n|\r|\f
+w         [ \t\r\n\f]*
+
+%%
+
+[ \t\r\n\f]+     return S;
+
+"~="             return INCLUDES;
+"|="             return DASHMATCH;
+"^="             return PREFIXMATCH;
+"$="             return SUFFIXMATCH;
+"*="             return SUBSTRINGMATCH;
+{ident}          return IDENT;
+{string}         return STRING;
+{ident}"("       return FUNCTION;
+{num}            return NUMBER;
+"#"{name}        return HASH;
+{w}"+"           return PLUS;
+{w}">"           return GREATER;
+{w}","           return COMMA;
+{w}"~"           return TILDE;
+":not("          return NOT;
+@{ident}         return ATKEYWORD;
+{invalid}        return INVALID;
+{num}%           return PERCENTAGE;
+{num}{ident}     return DIMENSION;
+"<!--"           return CDO;
+"-->"            return CDC;
+
+"url("{w}{string}{w}")"                           return URI;
+"url("{w}([!#$%&*-~]|{nonascii}|{escape})*{w}")"  return URI;
+U\+[0-9a-f?]{1,6}(-[0-9a-f]{1,6})?                return UNICODE_RANGE;
+
+\/\*[^*]*\*+([^/*][^*]*\*+)*\/                    /* ignore comments */
+
+.                return *yytext;
+ + + +

11. Namespaces and down-level clients

+ +

An important issue is the interaction of CSS selectors with XML +documents in web clients that were produced prior to this +document. Unfortunately, due to the fact that namespaces must be +matched based on the URI which identifies the namespace, not the +namespace prefix, some mechanism is required to identify namespaces in +CSS by their URI as well. Without such a mechanism, it is impossible +to construct a CSS style sheet which will properly match selectors in +all cases against a random set of XML documents. However, given +complete knowledge of the XML document to which a style sheet is to be +applied, and a limited use of namespaces within the XML document, it +is possible to construct a style sheet in which selectors would match +elements and attributes correctly.

+ +

It should be noted that a down-level CSS client will (if it +properly conforms to CSS forward compatible parsing rules) ignore all +@namespace at-rules, as well as all style rules that make +use of namespace qualified element type or attribute selectors. The +syntax of delimiting namespace prefixes in CSS was deliberately chosen +so that down-level CSS clients would ignore the style rules rather +than possibly match them incorrectly.

+ +

The use of default namespaces in CSS makes it possible to write +element type selectors that will function in both namespace aware CSS +clients as well as down-level clients. It should be noted that +down-level clients may incorrectly match selectors against XML +elements in other namespaces.

+ +

The following are scenarios and examples in which it is possible to +construct style sheets which would function properly in web clients +that do not implement this proposal.

+ +
    +
  1. + +

    The XML document does not use namespaces.

    + +
      + +
    • In this case, it is obviously not necessary to declare or use + namespaces in the style sheet. Standard CSS element type and + attribute selectors will function adequately in a down-level + client.
    • + +
    • In a CSS namespace aware client, the default behavior of + element selectors matching without regard to namespace will + function properly against all elements, since no namespaces are + present. However, the use of specific element type selectors that + match only elements that have no namespace ("|name") + will guarantee that selectors will match only XML elements that do + not have a declared namespace.
    • + +
    + +
  2. + +
  3. + +

    The XML document defines a single, default namespace used + throughout the document. No namespace prefixes are used in element + names.

    + +
      + +
    • In this case, a down-level client will function as if + namespaces were not used in the XML document at all. Standard CSS + element type and attribute selectors will match against all + elements.
    • + +
    + +
  4. + +
  5. + +

    The XML document does not use a default namespace, all + namespace prefixes used are known to the style sheet author, and + there is a direct mapping between namespace prefixes and namespace + URIs. (A given prefix may only be mapped to one namespace URI + throughout the XML document; there may be multiple prefixes mapped + to the same URI).

    + +
      + +
    • In this case, the down-level client will view and match + element type and attribute selectors based on their fully + qualified name, not the local part as outlined in the Type selectors and Namespaces section. CSS + selectors may be declared using an escaped colon "\:" + to describe the fully qualified names, e.g. + "html\:h1" will match + <html:h1>. Selectors using the qualified name + will only match XML elements that use the same prefix. Other + namespace prefixes used in the XML that are mapped to the same URI + will not match as expected unless additional CSS style rules are + declared for them.
    • + +
    • Note that selectors declared in this fashion will + only match in down-level clients. A CSS namespace aware + client will match element type and attribute selectors based on + the name's local part. Selectors declared with the fully + qualified name will not match (unless there is no namespace prefix + in the fully qualified name).
    • + +
    + +
  6. + +
+ +

In other scenarios: when the namespace prefixes used in the XML are +not known in advance by the style sheet author; or a combination of +elements with no namespace are used in conjunction with elements using +a default namespace; or the same namespace prefix is mapped to +different namespace URIs within the same document, or in +different documents; it is impossible to construct a CSS style sheet +that will function properly against all elements in those documents, +unless, the style sheet is written using a namespace URI syntax (as +outlined in this document or similar) and the document is processed by +a CSS and XML namespace aware client.

+ +

12. Profiles

+ +

Each specification using Selectors must define the subset of W3C +Selectors it allows and excludes, and describe the local meaning of +all the components of that subset.

+ +

Non normative examples: + +

+ + + + + + + + + + + + + + + +
Selectors profile
SpecificationCSS level 1
Acceptstype selectors
class selectors
ID selectors
:link, + :visited and :active pseudo-classes
descendant combinator +
::first-line and ::first-letter pseudo-elements
Excludes + +

universal selector
attribute selectors
:hover and :focus + pseudo-classes
:target pseudo-class
:lang() pseudo-class
all UI + element states pseudo-classes
all structural + pseudo-classes
negation pseudo-class
all + UI element fragments pseudo-elements
::before and ::after + pseudo-elements
child combinators
sibling combinators + +

namespaces

Extra constraintsonly one class selector allowed per sequence of simple + selectors


+ + + + + + + + + + + + + + + +
Selectors profile
SpecificationCSS level 2
Acceptstype selectors
universal selector
attribute presence and + values selectors
class selectors
ID selectors
:link, :visited, + :active, :hover, :focus, :lang() and :first-child pseudo-classes +
descendant combinator
child combinator
adjacent sibling + combinator
::first-line and ::first-letter pseudo-elements
::before + and ::after pseudo-elements
Excludes + +

content selectors
substring matching attribute + selectors
:target pseudo-classes
all UI element + states pseudo-classes
all structural pseudo-classes other + than :first-child
negation pseudo-class
all UI element + fragments pseudo-elements
general sibling combinators + +

namespaces

Extra constraintsmore than one class selector per sequence of simple selectors (CSS1 + constraint) allowed
+ +

In CSS, selectors express pattern matching rules that determine which style +rules apply to elements in the document tree. + +

The following selector (CSS level 2) will match all anchors a +with attribute name set inside a section 1 header h1: +

h1 a[name]
+ +

All CSS declarations attached to such a selector are applied to elements +matching it.

+ +
+ + + + + + + + + + + + + + + + +
Selectors profile
SpecificationSTTS 3
Accepts + +

type selectors
universal selectors
attribute selectors
class + selectors
ID selectors
all structural pseudo-classes
+ all combinators + +

namespaces

Excludesnon-accepted pseudo-classes
pseudo-elements
Extra constraintssome selectors and combinators are not allowed in fragment + descriptions on the right side of STTS declarations.
+ +

Selectors can be used in STTS 3 in two different + manners: +

    +
  1. a selection mechanism equivalent to CSS selection mechanism: declarations + attached to a given selector are applied to elements matching that selector, +
  2. fragment descriptions that appear on the right side of declarations. +
+ +

13. Conformance and requirements

+ +

This section defines conformance with the present specification only. + +

The inability of a user agent to implement part of this specification due to +the limitations of a particular device (e.g., non interactive user agents will +probably not implement dynamic pseudo-classes because they make no sense without +interactivity) does not imply non-conformance. + +

All specifications reusing Selectors must contain a Profile listing the +subset of Selectors it accepts or excludes, and describing the constraints +it adds to the current specification. + +

Invalidity is caused by a parsing error, e.g. an unrecognized token or a token +which is not allowed at the current parsing point. + +

User agents must observe the rules for handling parsing errors: +

+ +

Specifications reusing Selectors must define how to handle parsing +errors. (In the case of CSS, the entire rule in which the selector is +used is dropped.)

+ + + +

14. Tests

+ +

This specification has a test +suite allowing user agents to verify their basic conformance to +the specification. This test suite does not pretend to be exhaustive +and does not cover all possible combined cases of Selectors.

+ +

15. Acknowledgements

+ +

The CSS working group would like to thank everyone who has sent +comments on this specification over the years.

+ +

The working group would like to extend special thanks to Donna +McManus, Justin Baker, Joel Sklar, and Molly Ives Brower who perfermed +the final editorial review.

+ +

16. References

+ +
+ +
[CSS1] +
Bert Bos, Håkon Wium Lie; "Cascading Style Sheets, level 1", W3C Recommendation, 17 Dec 1996, revised 11 Jan 1999 +
(http://www.w3.org/TR/REC-CSS1) + +
[CSS21] +
Bert Bos, Tantek Çelik, Ian Hickson, Håkon Wium Lie, editors; "Cascading Style Sheets, level 2 revision 1", W3C Working Draft, 13 June 2005 +
(http://www.w3.org/TR/CSS21) + +
[CWWW] +
Martin J. Dürst, François Yergeau, Misha Wolf, Asmus Freytag, Tex Texin, editors; "Character Model for the World Wide Web", W3C Recommendation, 15 February 2005 +
(http://www.w3.org/TR/charmod/) + +
[FLEX] +
"Flex: The Lexical Scanner Generator", Version 2.3.7, ISBN 1882114213 + +
[HTML4] +
Dave Ragget, Arnaud Le Hors, Ian Jacobs, editors; "HTML 4.01 Specification", W3C Recommendation, 24 December 1999 +
(http://www.w3.org/TR/html4/) + +
[MATH] +
Patrick Ion, Robert Miner, editors; "Mathematical Markup Language (MathML) 1.01", W3C Recommendation, revision of 7 July 1999 +
(http://www.w3.org/TR/REC-MathML/) + +
[RFC3066] +
H. Alvestrand; "Tags for the Identification of Languages", Request for Comments 3066, January 2001 +
(http://www.ietf.org/rfc/rfc3066.txt) + +
[STTS] +
Daniel Glazman; "Simple Tree Transformation Sheets 3", Electricité de France, submission to the W3C, 11 November 1998 +
(http://www.w3.org/TR/NOTE-STTS3) + +
[SVG] +
Jon Ferraiolo, 藤沢 淳, Dean Jackson, editors; "Scalable Vector Graphics (SVG) 1.1 Specification", W3C Recommendation, 14 January 2003 +
(http://www.w3.org/TR/SVG/) + +
[UNICODE]
+
The Unicode Standard, Version 4.1, The Unicode Consortium. Boston, MA, Addison-Wesley, March 2005. ISBN 0-321-18578-1, as amended by Unicode 4.0.1 and Unicode 4.1.0. +
(http://www.unicode.org/versions/)
+ +
[XML10] +
Tim Bray, Jean Paoli, C. M. Sperberg-McQueen, Eve Maler, François Yergeau, editors; "Extensible Markup Language (XML) 1.0 (Third Edition)", W3C Recommendation, 4 February 2004 +
(http://www.w3.org/TR/REC-xml/) + +
[XMLNAMES] +
Tim Bray, Dave Hollander, Andrew Layman, editors; "Namespaces in XML", W3C Recommendation, 14 January 1999 +
(http://www.w3.org/TR/REC-xml-names/) + +
[YACC] +
S. C. Johnson; "YACC — Yet another compiler compiler", Technical Report, Murray Hill, 1975 + +
+ +
+ test +
+
+
+ test +
+ test +
+
+
+ test +
+
+
+
+ +
+ d1d1 + d2d2 + d3d3 + d4d4 + d5d5 + d6d6 + + + + + + +
+
+ d1 + d1 + + d2 + d2 + + d3 + d3 + + d4 + d4 + + d5 + d5 + + d6 + d6 + +
+ + + diff --git a/test_new/browser/fixtures/slick/template.xhtml b/test_new/browser/fixtures/slick/template.xhtml new file mode 100644 index 0000000..07d9669 --- /dev/null +++ b/test_new/browser/fixtures/slick/template.xhtml @@ -0,0 +1,2476 @@ + + + + + + + + template xhtml as xhtml + + + + +
+

W3C

+ +

Selectors

+ +

W3C Working Draft 15 December 2005

+ +
+
This version:
+ +
http://www.w3.org/TR/2005/WD-css3-selectors-20051215
+ +
Latest version:
+ +
http://www.w3.org/TR/css3-selectors
+ +
Previous version:
+ +
http://www.w3.org/TR/2001/CR-css3-selectors-20011113
+ +
Editors:
+ +
Daniel Glazman (Invited Expert)
+ +
Tantek Çelik (Invited Expert)
+ +
Ian Hickson (Google)
+ +
Peter Linss (former editor, Netscape/AOL)
+ +
John Williams (former editor, Quark, Inc.)
+
+ + +
+
+ +

Abstract

+ +

Selectors are patterns that match against elements in a tree. Selectors have been optimized for use with HTML and XML, and are designed to be usable in performance-critical code.

+ +

CSS (Cascading Style Sheets) is a language for describing the rendering of HTML and XML documents on screen, on paper, in speech, etc. CSS uses Selectors for binding style properties to elements in the document. This document describes extensions to the selectors defined in CSS level 2. These extended selectors will be used by CSS level 3.

+ +

Selectors define the following function:

+
+expression ∗ element → boolean
+
+ +

That is, given an element and a selector, this specification defines whether that element matches the selector.

+ +

These expressions can also be used, for instance, to select a set of elements, or a single element from a set of elements, by evaluating the expression across all the elements in a subtree. STTS (Simple Tree Transformation Sheets), a language for transforming XML trees, uses this mechanism. [STTS]

+ +

Status of this document

+ +

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

+ +

This document describes the selectors that already exist in CSS1 and CSS2, and also proposes new selectors for CSS3 and other languages that may need them.

+ +

The CSS Working Group doesn't expect that all implementations of CSS3 will have to implement all selectors. Instead, there will probably be a small number of variants of CSS3, called profiles. For example, it may be that only a profile for interactive user agents will include all of the selectors.

+ +

This specification is a last call working draft for the the CSS Working Group (Style Activity). This document is a revision of the Candidate Recommendation dated 2001 November 13, and has incorporated implementation feedback received in the past few years. It is expected that this last call will proceed straight to Proposed Recommendation stage since it is believed that interoperability will be demonstrable.

+ +

All persons are encouraged to review and implement this specification and return comments to the (archived) public mailing list www-style (see instructions). W3C Members can also send comments directly to the CSS Working Group. The deadline for comments is 14 January 2006.

+ +

This is still a draft document and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to cite a W3C Working Draft as other than "work in progress".

+ +

This document may be available in translation. The English version of this specification is the only normative version.

+ +
+

Table of contents

+ + +
+ +

1. Introduction

+ +

1.1. Dependencies

+ +

Some features of this specification are specific to CSS, or have particular limitations or rules specific to CSS. In this specification, these have been described in terms of CSS2.1. [CSS21]

+ +

1.2. Terminology

+ +

All of the text of this specification is normative except examples, notes, and sections explicitly marked as non-normative.

+ +

1.3. Changes from CSS2

+ +

This section is non-normative.

+ +

The main differences between the selectors in CSS2 and those in Selectors are:

+ + + +

2. Selectors

+ +

This section is non-normative, as it merely summarizes the following sections.

+ +

A Selector represents a structure. This structure can be used as a condition (e.g. in a CSS rule) that determines which elements a selector matches in the document tree, or as a flat description of the HTML or XML fragment corresponding to that structure.

+ +

Selectors may range from simple element names to rich contextual representations.

+ +

The following table summarizes the Selector syntax:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PatternMeaningDescribed in sectionFirst defined in CSS level
*any elementUniversal selector2
Ean element of type EType selector1
E[foo]an E element with a "foo" attributeAttribute selectors2
E[foo="bar"]an E element whose "foo" attribute value is exactly equal to "bar"Attribute selectors2
E[foo~="bar"]an E element whose "foo" attribute value is a list of space-separated values, one of which is exactly equal to "bar"Attribute selectors2
E[foo^="bar"]an E element whose "foo" attribute value begins exactly with the string "bar"Attribute selectors3
E[foo$="bar"]an E element whose "foo" attribute value ends exactly with the string "bar"Attribute selectors3
E[foo*="bar"]an E element whose "foo" attribute value contains the substring "bar"Attribute selectors3
E[hreflang|="en"]an E element whose "hreflang" attribute has a hyphen-separated list of values beginning (from the left) with "en"Attribute selectors2
E:rootan E element, root of the documentStructural pseudo-classes3
E:nth-child(n)an E element, the n-th child of its parentStructural pseudo-classes3
E:nth-last-child(n)an E element, the n-th child of its parent, counting from the last oneStructural pseudo-classes3
E:nth-of-type(n)an E element, the n-th sibling of its typeStructural pseudo-classes3
E:nth-last-of-type(n)an E element, the n-th sibling of its type, counting from the last oneStructural pseudo-classes3
E:first-childan E element, first child of its parentStructural pseudo-classes2
E:last-childan E element, last child of its parentStructural pseudo-classes3
E:first-of-typean E element, first sibling of its typeStructural pseudo-classes3
E:last-of-typean E element, last sibling of its typeStructural pseudo-classes3
E:only-childan E element, only child of its parentStructural pseudo-classes3
E:only-of-typean E element, only sibling of its typeStructural pseudo-classes3
E:emptyan E element that has no children (including text nodes)Structural pseudo-classes3
E:link
+ E:visited
an E element being the source anchor of a hyperlink of which the target is not yet visited (:link) or already visited (:visited)The link pseudo-classes1
E:active
+ E:hover
+ E:focus
an E element during certain user actionsThe user action pseudo-classes1 and 2
E:targetan E element being the target of the referring URIThe target pseudo-class3
E:lang(fr)an element of type E in language "fr" (the document language specifies how language is determined)The :lang() pseudo-class2
E:enabled
+ E:disabled
a user interface element E which is enabled or disabledThe UI element states pseudo-classes3
E:checkeda user interface element E which is checked (for instance a radio-button or checkbox)The UI element states pseudo-classes3
E::first-linethe first formatted line of an E elementThe ::first-line pseudo-element1
E::first-letterthe first formatted letter of an E elementThe ::first-letter pseudo-element1
E::selectionthe portion of an E element that is currently selected/highlighted by the userThe UI element fragments pseudo-elements3
E::beforegenerated content before an E elementThe ::before pseudo-element2
E::aftergenerated content after an E elementThe ::after pseudo-element2
E.warningan E element whose class is "warning" (the document language specifies how class is determined).Class selectors1
E#myidan E element with ID equal to "myid".ID selectors1
E:not(s)an E element that does not match simple selector sNegation pseudo-class3
E Fan F element descendant of an E elementDescendant combinator1
E > Fan F element child of an E elementChild combinator2
E + Fan F element immediately preceded by an E elementAdjacent sibling combinator2
E ~ Fan F element preceded by an E elementGeneral sibling combinator3
+ +

The meaning of each selector is derived from the table above by prepending "matches" to the contents of each cell in the "Meaning" column.

+ +

3. Case sensitivity

+ +

The case sensitivity of document language element names, attribute names, and attribute values in selectors depends on the document language. For example, in HTML, element names are case-insensitive, but in XML, they are case-sensitive.

+ +

4. Selector syntax

+ +

A selector is a chain of one or more sequences of simple selectors separated by combinators.

+ +

A sequence of simple selectors is a chain of simple selectors that are not separated by a combinator. It always begins with a type selector or a universal selector. No other type selector or universal selector is allowed in the sequence.

+ +

A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, content selector, or pseudo-class. One pseudo-element may be appended to the last sequence of simple selectors.

+ +

Combinators are: white space, "greater-than sign" (U+003E, >), "plus sign" (U+002B, +) and "tilde" (U+007E, ~). White space may appear between a combinator and the simple selectors around it. Only the characters "space" (U+0020), "tab" (U+0009), "line feed" (U+000A), "carriage return" (U+000D), and "form feed" (U+000C) can occur in white space. Other space-like characters, such as "em-space" (U+2003) and "ideographic space" (U+3000), are never part of white space.

+ +

The elements of a document tree that are represented by a selector are the subjects of the selector. A selector consisting of a single sequence of simple selectors represents any element satisfying its requirements. Prepending another sequence of simple selectors and a combinator to a sequence imposes additional matching constraints, so the subjects of a selector are always a subset of the elements represented by the last sequence of simple selectors.

+ +

An empty selector, containing no sequence of simple selectors and no pseudo-element, is an invalid selector.

+ +

5. Groups of selectors

+ +

When several selectors share the same declarations, they may be grouped into a comma-separated list. (A comma is U+002C.)

+ +
+

CSS examples:

+ +

In this example, we condense three rules with identical declarations into one. Thus,

+
+h1 { font-family: sans-serif }
+h2 { font-family: sans-serif }
+h3 { font-family: sans-serif }
+
+ +

is equivalent to:

+
+h1, h2, h3 { font-family: sans-serif }
+
+
+ +

Warning: the equivalence is true in this example because all the selectors are valid selectors. If just one of these selectors were invalid, the entire group of selectors would be invalid. This would invalidate the rule for all three heading elements, whereas in the former case only one of the three individual heading rules would be invalidated.

+ +

6. Simple selectors

+ +

6.1. Type selector

+ +

A type selector is the name of a document language element type. A type selector represents an instance of the element type in the document tree.

+ +
+

Example:

+ +

The following selector represents an h1 element in the document tree:

+
+h1
+
+
+ +

6.1.1. Type selectors and namespaces

+ +

Type selectors allow an optional namespace ([XMLNAMES]) component. A namespace prefix that has been previously declared may be prepended to the element name separated by the namespace separator "vertical bar" (U+007C, |).

+ +

The namespace component may be left empty to indicate that the selector is only to represent elements with no declared namespace.

+ +

An asterisk may be used for the namespace prefix, indicating that the selector represents elements in any namespace (including elements with no namespace).

+ +

Element type selectors that have no namespace component (no namespace separator), represent elements without regard to the element's namespace (equivalent to "*|") unless a default namespace has been declared. If a default namespace has been declared, the selector will represent only elements in the default namespace.

+ +

A type selector containing a namespace prefix that has not been previously declared is an invalid selector. The mechanism for declaring a namespace prefix is left up to the language implementing Selectors. In CSS, such a mechanism is defined in the General Syntax module.

+ +

In a namespace-aware client, element type selectors will only match against the local part of the element's qualified name. See below for notes about matching behaviors in down-level clients.

+ +

In summary:

+ +
+
ns|E
+ +
elements with name E in namespace ns
+ +
*|E
+ +
elements with name E in any namespace, including those without any declared namespace
+ +
|E
+ +
elements with name E without any declared namespace
+ +
E
+ +
if no default namespace has been specified, this is equivalent to *|E. Otherwise it is equivalent to ns|E where ns is the default namespace.
+
+ +
+

CSS examples:

+
+@namespace foo url(http://www.example.com);
+ foo|h1 { color: blue }
+ foo|* { color: yellow }
+ |h1 { color: red }
+ *|h1 { color: green }
+ h1 { color: green }
+
+ +

The first rule will match only h1 elements in the "http://www.example.com" namespace.

+ +

The second rule will match all elements in the "http://www.example.com" namespace.

+ +

The third rule will match only h1 elements without any declared namespace.

+ +

The fourth rule will match h1 elements in any namespace (including those without any declared namespace).

+ +

The last rule is equivalent to the fourth rule because no default namespace has been defined.

+
+ +

6.2. Universal selector

+ +

The universal selector, written "asterisk" (*), represents the qualified name of any element type. It represents any single element in the document tree in any namespace (including those without any declared namespace) if no default namespace has been specified. If a default namespace has been specified, see Universal selector and Namespaces below.

+ +

If the universal selector is not the only component of a sequence of simple selectors, the * may be omitted.

+ +
+

Examples:

+ +
    +
  • *[hreflang|=en] and [hreflang|=en] are equivalent,
  • + +
  • *.warning and .warning are equivalent,
  • + +
  • *#myid and #myid are equivalent.
  • +
+
+ +

Note: it is recommended that the *, representing the universal selector, not be omitted.

+ +

6.2.1. Universal selector and namespaces

+ +

The universal selector allows an optional namespace component. It is used as follows:

+ +
+
ns|*
+ +
all elements in namespace ns
+ +
*|*
+ +
all elements
+ +
|*
+ +
all elements without any declared namespace
+ +
*
+ +
if no default namespace has been specified, this is equivalent to *|*. Otherwise it is equivalent to ns|* where ns is the default namespace.
+
+ +

A universal selector containing a namespace prefix that has not been previously declared is an invalid selector. The mechanism for declaring a namespace prefix is left up to the language implementing Selectors. In CSS, such a mechanism is defined in the General Syntax module.

+ +

6.3. Attribute selectors

+ +

Selectors allow the representation of an element's attributes. When a selector is used as an expression to match against an element, attribute selectors must be considered to match an element if that element has an attribute that matches the attribute represented by the attribute selector.

+ +

6.3.1. Attribute presence and values selectors

+ +

CSS2 introduced four attribute selectors:

+ +
+
[att]
+ +
Represents an element with the att attribute, whatever the value of the attribute.
+ +
[att=val]
+ +
Represents an element with the att attribute whose value is exactly "val".
+ +
[att~=val]
+ +
Represents an element with the att attribute whose value is a whitespace-separated list of words, one of which is exactly "val". If "val" contains whitespace, it will never represent anything (since the words are separated by spaces).
+ +
[att|=val]
+ +
Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D). This is primarily intended to allow language subcode matches (e.g., the hreflang attribute on the link element in HTML) as described in RFC 3066 ([RFC3066]). For lang (or xml:lang) language subcode matching, please see the :lang pseudo-class.
+
+ +

Attribute values must be identifiers or strings. The case-sensitivity of attribute names and values in selectors depends on the document language.

+ +
+

Examples:

+ +

The following attribute selector represents an h1 element that carries the title attribute, whatever its value:

+
+h1[title]
+
+ +

In the following example, the selector represents a span element whose class attribute has exactly the value "example":

+
+span[class="example"]
+
+ +

Multiple attribute selectors can be used to represent several attributes of an element, or several conditions on the same attribute. Here, the selector represents a span element whose hello attribute has exactly the value "Cleveland" and whose goodbye attribute has exactly the value "Columbus":

+
+span[hello="Cleveland"][goodbye="Columbus"]
+
+ +

The following selectors illustrate the differences between "=" and "~=". The first selector will represent, for example, the value "copyright copyleft copyeditor" on a rel attribute. The second selector will only represent an a element with an href attribute having the exact value "http://www.w3.org/".

+
+a[rel~="copyright"]
+a[href="http://www.w3.org/"]
+
+ +

The following selector represents a link element whose hreflang attribute is exactly "fr".

+
+link[hreflang=fr]
+
+ +

The following selector represents a link element for which the values of the hreflang attribute begins with "en", including "en", "en-US", and "en-cockney":

+
+link[hreflang|="en"]
+
+ +

Similarly, the following selectors represents a DIALOGUE element whenever it has one of two different values for an attribute character:

+
+DIALOGUE[character=romeo]
+DIALOGUE[character=juliet]
+
+
+ +

6.3.2. Substring matching attribute selectors

+ +

Three additional attribute selectors are provided for matching substrings in the value of an attribute:

+ +
+
[att^=val]
+ +
Represents an element with the att attribute whose value begins with the prefix "val".
+ +
[att$=val]
+ +
Represents an element with the att attribute whose value ends with the suffix "val".
+ +
[att*=val]
+ +
Represents an element with the att attribute whose value contains at least one instance of the substring "val".
+
+ +

Attribute values must be identifiers or strings. The case-sensitivity of attribute names in selectors depends on the document language.

+ +
+

Examples:

+ +

The following selector represents an HTML object, referencing an image:

+
+object[type^="image/"]
+
+ +

The following selector represents an HTML anchor a with an href attribute whose value ends with ".html".

+
+a[href$=".html"]
+
+ +

The following selector represents an HTML paragraph with a title attribute whose value contains the substring "hello"

+
+p[title*="hello"]
+
+
+ +

6.3.3. Attribute selectors and namespaces

+ +

Attribute selectors allow an optional namespace component to the attribute name. A namespace prefix that has been previously declared may be prepended to the attribute name separated by the namespace separator "vertical bar" (|). In keeping with the Namespaces in the XML recommendation, default namespaces do not apply to attributes, therefore attribute selectors without a namespace component apply only to attributes that have no declared namespace (equivalent to "|attr"). An asterisk may be used for the namespace prefix indicating that the selector is to match all attribute names without regard to the attribute's namespace.

+ +

An attribute selector with an attribute name containing a namespace prefix that has not been previously declared is an invalid selector. The mechanism for declaring a namespace prefix is left up to the language implementing Selectors. In CSS, such a mechanism is defined in the General Syntax module.

+ +
+

CSS examples:

+
+@namespace foo "http://www.example.com";
+[foo|att=val] { color: blue }
+[*|att] { color: yellow }
+[|att] { color: green }
+[att] { color: green }
+
+ +

The first rule will match only elements with the attribute att in the "http://www.example.com" namespace with the value "val".

+ +

The second rule will match only elements with the attribute att regardless of the namespace of the attribute (including no declared namespace).

+ +

The last two rules are equivalent and will match only elements with the attribute att where the attribute is not declared to be in a namespace.

+
+ +

6.3.4. Default attribute values in DTDs

+ +

Attribute selectors represent explicitly set attribute values in the document tree. Default attribute values may be defined in a DTD or elsewhere, but cannot always be selected by attribute selectors. Selectors should be designed so that they work even if the default values are not included in the document tree.

+ +

More precisely, a UA is not required to read an "external subset" of the DTD but is required to look for default attribute values in the document's "internal subset." (See [XML10] for definitions of these subsets.)

+ +

A UA that recognizes an XML namespace [XMLNAMES] is not required to use its knowledge of that namespace to treat default attribute values as if they were present in the document. (For example, an XHTML UA is not required to use its built-in knowledge of the XHTML DTD.)

+ +

Note: Typically, implementations choose to ignore external subsets.

+ +
+

Example:

+ +

Consider an element EXAMPLE with an attribute "notation" that has a default value of "decimal". The DTD fragment might be

+
+<!ATTLIST EXAMPLE notation (decimal,octal) "decimal">
+
+ +

If the style sheet contains the rules

+
+EXAMPLE[notation=decimal] { /*... default property settings ...*/ }
+EXAMPLE[notation=octal]   { /*... other settings...*/ }
+
+ +

the first rule will not match elements whose "notation" attribute is set by default, i.e. not set explicitly. To catch all cases, the attribute selector for the default value must be dropped:

+
+EXAMPLE                   { /*... default property settings ...*/ }
+EXAMPLE[notation=octal]   { /*... other settings...*/ }
+
+ +

Here, because the selector EXAMPLE[notation=octal] is more specific than the tag selector alone, the style declarations in the second rule will override those in the first for elements that have a "notation" attribute value of "octal". Care has to be taken that all property declarations that are to apply only to the default case are overridden in the non-default cases' style rules.

+
+ +

6.4. Class selectors

+ +

Working with HTML, authors may use the period (U+002E, .) notation as an alternative to the ~= notation when representing the class attribute. Thus, for HTML, div.value and div[class~=value] have the same meaning. The attribute value must immediately follow the "period" (.).

+ +

UAs may apply selectors using the period (.) notation in XML documents if the UA has namespace-specific knowledge that allows it to determine which attribute is the "class" attribute for the respective namespace. One such example of namespace-specific knowledge is the prose in the specification for a particular namespace (e.g. SVG 1.0 [SVG] describes the SVG "class" attribute and how a UA should interpret it, and similarly MathML 1.01 [MATH] describes the MathML "class" attribute.)

+ +
+

CSS examples:

+ +

We can assign style information to all elements with class~="pastoral" as follows:

+
+*.pastoral { color: green }  /* all elements with class~=pastoral */
+
+ +

or just

+
+.pastoral { color: green }  /* all elements with class~=pastoral */
+
+ +

The following assigns style only to H1 elements with class~="pastoral":

+
+H1.pastoral { color: green }  /* H1 elements with class~=pastoral */
+
+ +

Given these rules, the first H1 instance below would not have green text, while the second would:

+
+<H1>Not green</H1>
+<H1 class="pastoral">Very green</H1>
+
+
+ +

To represent a subset of "class" values, each value must be preceded by a ".", in any order.

+ +
+

CSS example:

+ +

The following rule matches any P element whose "class" attribute has been assigned a list of whitespace-separated values that includes "pastoral" and "marine":

+
+p.pastoral.marine { color: green }
+
+ +

This rule matches when class="pastoral blue aqua marine" but does not match for class="pastoral blue".

+
+ +

Note: Because CSS gives considerable power to the "class" attribute, authors could conceivably design their own "document language" based on elements with almost no associated presentation (such as DIV and SPAN in HTML) and assigning style information through the "class" attribute. Authors should avoid this practice since the structural elements of a document language often have recognized and accepted meanings and author-defined classes may not.

+ +

Note: If an element has multiple class attributes, their values must be concatenated with spaces between the values before searching for the class. As of this time the working group is not aware of any manner in which this situation can be reached, however, so this behavior is explicitly non-normative in this specification.

+ +

6.5. ID selectors

+ +

Document languages may contain attributes that are declared to be of type ID. What makes attributes of type ID special is that no two such attributes can have the same value in a document, regardless of the type of the elements that carry them; whatever the document language, an ID typed attribute can be used to uniquely identify its element. In HTML all ID attributes are named "id"; XML applications may name ID attributes differently, but the same restriction applies.

+ +

An ID-typed attribute of a document language allows authors to assign an identifier to one element instance in the document tree. W3C ID selectors represent an element instance based on its identifier. An ID selector contains a "number sign" (U+0023, #) immediately followed by the ID value, which must be an identifier.

+ +

Selectors does not specify how a UA knows the ID-typed attribute of an element. The UA may, e.g., read a document's DTD, have the information hard-coded or ask the user.

+ +
+

Examples:

+ +

The following ID selector represents an h1 element whose ID-typed attribute has the value "chapter1":

+
+h1#chapter1
+
+ +

The following ID selector represents any element whose ID-typed attribute has the value "chapter1":

+
+#chapter1
+
+ +

The following selector represents any element whose ID-typed attribute has the value "z98y".

+
+*#z98y
+
+
+ +

Note. In XML 1.0 [XML10], the information about which attribute contains an element's IDs is contained in a DTD or a schema. When parsing XML, UAs do not always read the DTD, and thus may not know what the ID of an element is (though a UA may have namespace-specific knowledge that allows it to determine which attribute is the ID attribute for that namespace). If a style sheet designer knows or suspects that a UA may not know what the ID of an element is, he should use normal attribute selectors instead: [name=p371] instead of #p371. Elements in XML 1.0 documents without a DTD do not have IDs at all.

+ +

If an element has multiple ID attributes, all of them must be treated as IDs for that element for the purposes of the ID selector. Such a situation could be reached using mixtures of xml:id, DOM3 Core, XML DTDs, and namespace-specific knowledge.

+ +

6.6. Pseudo-classes

+ +

The pseudo-class concept is introduced to permit selection based on information that lies outside of the document tree or that cannot be expressed using the other simple selectors.

+ +

A pseudo-class always consists of a "colon" (:) followed by the name of the pseudo-class and optionally by a value between parentheses.

+ +

Pseudo-classes are allowed in all sequences of simple selectors contained in a selector. Pseudo-classes are allowed anywhere in sequences of simple selectors, after the leading type selector or universal selector (possibly omitted). Pseudo-class names are case-insensitive. Some pseudo-classes are mutually exclusive, while others can be applied simultaneously to the same element. Pseudo-classes may be dynamic, in the sense that an element may acquire or lose a pseudo-class while a user interacts with the document.

+ +

6.6.1. Dynamic pseudo-classes

+ +

Dynamic pseudo-classes classify elements on characteristics other than their name, attributes, or content, in principle characteristics that cannot be deduced from the document tree.

+ +

Dynamic pseudo-classes do not appear in the document source or document tree.

+ +
The link pseudo-classes: :link and :visited
+ +

User agents commonly display unvisited links differently from previously visited ones. Selectors provides the pseudo-classes :link and :visited to distinguish them:

+ + + +

After some amount of time, user agents may choose to return a visited link to the (unvisited) ':link' state.

+ +

The two states are mutually exclusive.

+ +
+

Example:

+ +

The following selector represents links carrying class external and already visited:

+
+a.external:visited
+
+
+ +

Note: It is possible for style sheet authors to abuse the :link and :visited pseudo-classes to determine which sites a user has visited without the user's consent.

+ +

UAs may therefore treat all links as unvisited links, or implement other measures to preserve the user's privacy while rendering visited and unvisited links differently.

+ +
The user action pseudo-classes :hover, :active, and :focus
+ +

Interactive user agents sometimes change the rendering in response to user actions. Selectors provides three pseudo-classes for the selection of an element the user is acting on.

+ + + +

There may be document language or implementation specific limits on which elements can become :active or acquire :focus.

+ +

These pseudo-classes are not mutually exclusive. An element may match several pseudo-classes at the same time.

+ +

Selectors doesn't define if the parent of an element that is ':active' or ':hover' is also in that state.

+ +
+

Examples:

+
+a:link    /* unvisited links */
+a:visited /* visited links */
+a:hover   /* user hovers */
+a:active  /* active links */
+
+ +

An example of combining dynamic pseudo-classes:

+
+a:focus
+a:focus:hover
+
+ +

The last selector matches a elements that are in the pseudo-class :focus and in the pseudo-class :hover.

+
+ +

Note: An element can be both ':visited' and ':active' (or ':link' and ':active').

+ +

6.6.2. The target pseudo-class :target

+ +

Some URIs refer to a location within a resource. This kind of URI ends with a "number sign" (#) followed by an anchor identifier (called the fragment identifier).

+ +

URIs with fragment identifiers link to a certain element within the document, known as the target element. For instance, here is a URI pointing to an anchor named section_2 in an HTML document:

+
+http://example.com/html/top.html#section_2
+
+ +

A target element can be represented by the :target pseudo-class. If the document's URI has no fragment identifier, then the document has no target element.

+ +
+

Example:

+
+p.note:target
+
+ +

This selector represents a p element of class note that is the target element of the referring URI.

+
+ +
+

CSS example:

+ +

Here, the :target pseudo-class is used to make the target element red and place an image before it, if there is one:

+
+*:target { color : red }
+*:target::before { content : url(target.png) }
+
+
+ +

6.6.3. The language pseudo-class :lang

+ +

If the document language specifies how the human language of an element is determined, it is possible to write selectors that represent an element based on its language. For example, in HTML [HTML4], the language is determined by a combination of the lang attribute, the meta element, and possibly by information from the protocol (such as HTTP headers). XML uses an attribute called xml:lang, and there may be other document language-specific methods for determining the language.

+ +

The pseudo-class :lang(C) represents an element that is in language C. Whether an element is represented by a :lang() selector is based solely on the identifier C being either equal to, or a hyphen-separated substring of, the element's language value, in the same way as if performed by the '|=' operator in attribute selectors. The identifier C does not have to be a valid language name.

+ +

C must not be empty. (If it is, the selector is invalid.)

+ +

Note: It is recommended that documents and protocols indicate language using codes from RFC 3066 [RFC3066] or its successor, and by means of "xml:lang" attributes in the case of XML-based documents [XML10]. See "FAQ: Two-letter or three-letter language codes."

+ +
+

Examples:

+ +

The two following selectors represent an HTML document that is in Belgian, French, or German. The two next selectors represent q quotations in an arbitrary element in Belgian, French, or German.

+
+html:lang(fr-be)
+html:lang(de)
+:lang(fr-be) > q
+:lang(de) > q
+
+
+ +

6.6.4. The UI element states pseudo-classes

+ +
The :enabled and :disabled pseudo-classes
+ +

The :enabled pseudo-class allows authors to customize the look of user interface elements that are enabled — which the user can select or activate in some fashion (e.g. clicking on a button with a mouse). There is a need for such a pseudo-class because there is no way to programmatically specify the default appearance of say, an enabled input element without also specifying what it would look like when it was disabled.

+ +

Similar to :enabled, :disabled allows the author to specify precisely how a disabled or inactive user interface element should look.

+ +

Most elements will be neither enabled nor disabled. An element is enabled if the user can either activate it or transfer the focus to it. An element is disabled if it could be enabled, but the user cannot presently activate it or transfer focus to it.

+ +
The :checked pseudo-class
+ +

Radio and checkbox elements can be toggled by the user. Some menu items are "checked" when the user selects them. When such elements are toggled "on" the :checked pseudo-class applies. The :checked pseudo-class initially applies to such elements that have the HTML4 selected and checked attributes as described in Section 17.2.1 of HTML4, but of course the user can toggle "off" such elements in which case the :checked pseudo-class would no longer apply. While the :checked pseudo-class is dynamic in nature, and is altered by user action, since it can also be based on the presence of the semantic HTML4 selected and checked attributes, it applies to all media.

+ +
The :indeterminate pseudo-class
+ +
+

Radio and checkbox elements can be toggled by the user, but are sometimes in an indeterminate state, neither checked nor unchecked. This can be due to an element attribute, or DOM manipulation.

+ +

A future version of this specification may introduce an :indeterminate pseudo-class that applies to such elements.

+
+ +

6.6.5. Structural pseudo-classes

+ +

Selectors introduces the concept of structural pseudo-classes to permit selection based on extra information that lies in the document tree but cannot be represented by other simple selectors or combinators.

+ +

Note that standalone pieces of PCDATA (text nodes in the DOM) are not counted when calculating the position of an element in the list of children of its parent. When calculating the position of an element in the list of children of its parent, the index numbering starts at 1.

+ +
:root pseudo-class
+ +

The :root pseudo-class represents an element that is the root of the document. In HTML 4, this is always the HTML element.

+ +
:nth-child() pseudo-class
+ +

The :nth-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree, for a given positive integer or zero value of n, and has a parent element. In other words, this matches the bth child of an element after all the children have been split into groups of a elements each. For example, this allows the selectors to address every other row in a table, and could be used to alternate the color of paragraph text in a cycle of four. The a and b values must be zero, negative integers or positive integers. The index of the first child of an element is 1.

+ +

In addition to this, :nth-child() can take 'odd' and 'even' as arguments instead. 'odd' has the same signification as 2n+1, and 'even' has the same signification as 2n.

+ +
+

Examples:

+
+tr:nth-child(2n+1) /* represents every odd row of an HTML table */
+tr:nth-child(odd)  /* same */
+tr:nth-child(2n)   /* represents every even row of an HTML table */
+tr:nth-child(even) /* same */
+
+/* Alternate paragraph colours in CSS */
+p:nth-child(4n+1) { color: navy; }
+p:nth-child(4n+2) { color: green; }
+p:nth-child(4n+3) { color: maroon; }
+p:nth-child(4n+4) { color: purple; }
+
+
+ +

When a=0, no repeating is used, so for example :nth-child(0n+5) matches only the fifth child. When a=0, the an part need not be included, so the syntax simplifies to :nth-child(b) and the last example simplifies to :nth-child(5).

+ +
+

Examples:

+
+foo:nth-child(0n+1)   /* represents an element foo, first child of its parent element */
+foo:nth-child(1)      /* same */
+
+
+ +

When a=1, the number may be omitted from the rule.

+ +
+

Examples:

+ +

The following selectors are therefore equivalent:

+
+bar:nth-child(1n+0)   /* represents all bar elements, specificity (0,1,1) */
+bar:nth-child(n+0)    /* same */
+bar:nth-child(n)      /* same */
+bar                   /* same but lower specificity (0,0,1) */
+
+
+ +

If b=0, then every ath element is picked. In such a case, the b part may be omitted.

+ +
+

Examples:

+
+tr:nth-child(2n+0) /* represents every even row of an HTML table */
+tr:nth-child(2n) /* same */
+
+
+ +

If both a and b are equal to zero, the pseudo-class represents no element in the document tree.

+ +

The value a can be negative, but only the positive values of an+b, for n≥0, may represent an element in the document tree.

+ +
+

Example:

+
+html|tr:nth-child(-n+6)  /* represents the 6 first rows of XHTML tables */
+
+
+ +

When the value b is negative, the "+" character in the expression must be removed (it is effectively replaced by the "-" character indicating the negative value of b).

+ +
+

Examples:

+
+:nth-child(10n-1)  /* represents the 9th, 19th, 29th, etc, element */
+:nth-child(10n+9)  /* Same */
+:nth-child(10n+-1) /* Syntactically invalid, and would be ignored */
+
+
+ +
:nth-last-child() pseudo-class
+ +

The :nth-last-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings after it in the document tree, for a given positive integer or zero value of n, and has a parent element. See :nth-child() pseudo-class for the syntax of its argument. It also accepts the 'even' and 'odd' values as arguments.

+ +
+

Examples:

+
+tr:nth-last-child(-n+2)    /* represents the two last rows of an HTML table */
+
+foo:nth-last-child(odd)    /* represents all odd foo elements in their parent element,
+                              counting from the last one */
+
+
+ +
:nth-of-type() pseudo-class
+ +

The :nth-of-type(an+b) pseudo-class notation represents an element that has an+b-1 siblings with the same element name before it in the document tree, for a given zero or positive integer value of n, and has a parent element. In other words, this matches the bth child of that type after all the children of that type have been split into groups of a elements each. See :nth-child() pseudo-class for the syntax of its argument. It also accepts the 'even' and 'odd' values.

+ +
+

CSS example:

+ +

This allows an author to alternate the position of floated images:

+
+img:nth-of-type(2n+1) { float: right; }
+img:nth-of-type(2n) { float: left; }
+
+
+ +
:nth-last-of-type() pseudo-class
+ +

The :nth-last-of-type(an+b) pseudo-class notation represents an element that has an+b-1 siblings with the same element name after it in the document tree, for a given zero or positive integer value of n, and has a parent element. See :nth-child() pseudo-class for the syntax of its argument. It also accepts the 'even' and 'odd' values.

+ +
+

Example:

+ +

To represent all h2 children of an XHTML body except the first and last, one could use the following selector:

+
+body > h2:nth-of-type(n+2):nth-last-of-type(n+2)
+
+ +

In this case, one could also use :not(), although the selector ends up being just as long:

+
+body > h2:not(:first-of-type):not(:last-of-type)
+
+
+ +
:first-child pseudo-class
+ +

Same as :nth-child(1). The :first-child pseudo-class represents an element that is the first child of some other element.

+ +
+

Examples:

+ +

The following selector represents a p element that is the first child of a div element:

+
+div > p:first-child
+
+ +

This selector can represent the p inside the div of the following fragment:

+
+<p> The last P before the note.</p>
+<div class="note">
+   <p> The first P inside the note.</p>
+</div>
+
but cannot represent the second p in the following fragment: +
+<p> The last P before the note.</p>
+<div class="note">
+   <h2> Note </h2>
+   <p> The first P inside the note.</p>
+</div>
+
+ +

The following two selectors are usually equivalent:

+
+* > a:first-child /* a is first child of any element */
+a:first-child /* Same (assuming a is not the root element) */
+
+
+ +
:last-child pseudo-class
+ +

Same as :nth-last-child(1). The :last-child pseudo-class represents an element that is the last child of some other element.

+ +
+

Example:

+ +

The following selector represents a list item li that is the last child of an ordered list ol.

+
+ol > li:last-child
+
+
+ +
:first-of-type pseudo-class
+ +

Same as :nth-of-type(1). The :first-of-type pseudo-class represents an element that is the first sibling of its type in the list of children of its parent element.

+ +
+

Example:

+ +

The following selector represents a definition title dt inside a definition list dl, this dt being the first of its type in the list of children of its parent element.

+
+dl dt:first-of-type
+
+ +

It is a valid description for the first two dt elements in the following example but not for the third one:

+
+<dl>
+ <dt>gigogne</dt>
+ <dd>
+  <dl>
+   <dt>fusée</dt>
+   <dd>multistage rocket</dd>
+   <dt>table</dt>
+   <dd>nest of tables</dd>
+  </dl>
+ </dd>
+</dl>
+
+
+ +
:last-of-type pseudo-class
+ +

Same as :nth-last-of-type(1). The :last-of-type pseudo-class represents an element that is the last sibling of its type in the list of children of its parent element.

+ +
+

Example:

+ +

The following selector represents the last data cell td of a table row.

+
+tr > td:last-of-type
+
+
+ +
:only-child pseudo-class
+ +

Represents an element that has a parent element and whose parent element has no other element children. Same as :first-child:last-child or :nth-child(1):nth-last-child(1), but with a lower specificity.

+ +
:only-of-type pseudo-class
+ +

Represents an element that has a parent element and whose parent element has no other element children with the same element name. Same as :first-of-type:last-of-type or :nth-of-type(1):nth-last-of-type(1), but with a lower specificity.

+ +
:empty pseudo-class
+ +

The :empty pseudo-class represents an element that has no children at all. In terms of the DOM, only element nodes and text nodes (including CDATA nodes and entity references) whose data has a non-zero length must be considered as affecting emptiness; comments, PIs, and other nodes must not affect whether an element is considered empty or not.

+ +
+

Examples:

+ +

p:empty is a valid representation of the following fragment:

+
+<p></p>
+
+ +

foo:empty is not a valid representation for the following fragments:

+
+<foo>bar</foo>
+
+
+<foo><bar>bla</bar></foo>
+
+
+<foo>this is not <bar>:empty</bar></foo>
+
+
+ +

6.6.6. Blank

+ +

This section intentionally left blank.

+ +

6.6.7. The negation pseudo-class

+ +

The negation pseudo-class, :not(X), is a functional notation taking a simple selector (excluding the negation pseudo-class itself and pseudo-elements) as an argument. It represents an element that is not represented by the argument.

+ +
+

Examples:

+ +

The following CSS selector matches all button elements in an HTML document that are not disabled.

+
+button:not([DISABLED])
+
+ +

The following selector represents all but FOO elements.

+
+*:not(FOO)
+
+ +

The following group of selectors represents all HTML elements except links.

+
+html|*:not(:link):not(:visited)
+
+
+ +

Default namespace declarations do not affect the argument of the negation pseudo-class unless the argument is a universal selector or a type selector.

+ +
+

Examples:

+ +

Assuming that the default namespace is bound to "http://example.com/", the following selector represents all elements that are not in that namespace:

+
+*|*:not(*)
+
+ +

The following CSS selector matches any element being hovered, regardless of its namespace. In particular, it is not limited to only matching elements in the default namespace that are not being hovered, and elements not in the default namespace don't match the rule when they are being hovered.

+
+*|*:not(:hover)
+
+
+ +

Note: the :not() pseudo allows useless selectors to be written. For instance :not(*|*), which represents no element at all, or foo:not(bar), which is equivalent to foo but with a higher specificity.

+ +

7. Pseudo-elements

+ +

Pseudo-elements create abstractions about the document tree beyond those specified by the document language. For instance, document languages do not offer mechanisms to access the first letter or first line of an element's content. Pseudo-elements allow designers to refer to this otherwise inaccessible information. Pseudo-elements may also provide designers a way to refer to content that does not exist in the source document (e.g., the ::before and ::after pseudo-elements give access to generated content).

+ +

A pseudo-element is made of two colons (::) followed by the name of the pseudo-element.

+ +

This :: notation is introduced by the current document in order to establish a discrimination between pseudo-classes and pseudo-elements. For compatibility with existing style sheets, user agents must also accept the previous one-colon notation for pseudo-elements introduced in CSS levels 1 and 2 (namely, :first-line, :first-letter, :before and :after). This compatibility is not allowed for the new pseudo-elements introduced in CSS level 3.

+ +

Only one pseudo-element may appear per selector, and if present it must appear after the sequence of simple selectors that represents the subjects of the selector. A future version of this specification may allow multiple pesudo-elements per selector.

+ +

7.1. The ::first-line pseudo-element

+ +

The ::first-line pseudo-element describes the contents of the first formatted line of an element.

+ +
+

CSS example:

+
+p::first-line { text-transform: uppercase }
+
+ +

The above rule means "change the letters of the first line of every paragraph to uppercase".

+
+ +

The selector p::first-line does not match any real HTML element. It does match a pseudo-element that conforming user agents will insert at the beginning of every paragraph.

+ +

Note that the length of the first line depends on a number of factors, including the width of the page, the font size, etc. Thus, an ordinary HTML paragraph such as:

+
+<P>This is a somewhat long HTML 
+paragraph that will be broken into several 
+lines. The first line will be identified
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

the lines of which happen to be broken as follows:

+
+THIS IS A SOMEWHAT LONG HTML PARAGRAPH THAT
+will be broken into several lines. The first
+line will be identified by a fictional tag 
+sequence. The other lines will be treated as 
+ordinary lines in the paragraph.
+
+ +

This paragraph might be "rewritten" by user agents to include the fictional tag sequence for ::first-line. This fictional tag sequence helps to show how properties are inherited.

+
+<P><P::first-line> This is a somewhat long HTML 
+paragraph that </P::first-line> will be broken into several
+lines. The first line will be identified 
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

If a pseudo-element breaks up a real element, the desired effect can often be described by a fictional tag sequence that closes and then re-opens the element. Thus, if we mark up the previous paragraph with a span element:

+
+<P><SPAN class="test"> This is a somewhat long HTML
+paragraph that will be broken into several
+lines.</SPAN> The first line will be identified
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

the user agent could simulate start and end tags for span when inserting the fictional tag sequence for ::first-line.

+
+<P><P::first-line><SPAN class="test"> This is a
+somewhat long HTML
+paragraph that will </SPAN></P::first-line><SPAN class="test"> be
+broken into several
+lines.</SPAN> The first line will be identified
+by a fictional tag sequence. The other lines
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

In CSS, the ::first-line pseudo-element can only be attached to a block-level element, an inline-block, a table-caption, or a table-cell.

+ +

The "first formatted line" of an element may occur inside a block-level descendant in the same flow (i.e., a block-level descendant that is not positioned and not a float). E.g., the first line of the div in <DIV><P>This line...</P></DIV> is the first line of the p (assuming that both p and div are block-level).

+ +

The first line of a table-cell or inline-block cannot be the first formatted line of an ancestor element. Thus, in <DIV><P STYLE="display: inline-block">Hello<BR>Goodbye</P> etcetera</DIV> the first formatted line of the div is not the line "Hello".

+ +

Note that the first line of the p in this fragment: <p><br>First... doesn't contain any letters (assuming the default style for br in HTML 4). The word "First" is not on the first formatted line.

+ +

A UA should act as if the fictional start tags of the ::first-line pseudo-elements were nested just inside the innermost enclosing block-level element. (Since CSS1 and CSS2 were silent on this case, authors should not rely on this behavior.) Here is an example. The fictional tag sequence for

+
+<DIV>
+  <P>First paragraph</P>
+  <P>Second paragraph</P>
+</DIV>
+
+ +

is

+
+<DIV>
+  <P><DIV::first-line><P::first-line>First paragraph</P::first-line></DIV::first-line></P>
+  <P><P::first-line>Second paragraph</P::first-line></P>
+</DIV>
+
+ +

The ::first-line pseudo-element is similar to an inline-level element, but with certain restrictions. In CSS, the following properties apply to a ::first-line pseudo-element: font properties, color property, background properties, 'word-spacing', 'letter-spacing', 'text-decoration', 'vertical-align', 'text-transform', 'line-height'. UAs may apply other properties as well.

+ +

7.2. The ::first-letter pseudo-element

+ +

The ::first-letter pseudo-element represents the first letter of the first line of a block, if it is not preceded by any other content (such as images or inline tables) on its line. The ::first-letter pseudo-element may be used for "initial caps" and "drop caps", which are common typographical effects. This type of initial letter is similar to an inline-level element if its 'float' property is 'none'; otherwise, it is similar to a floated element.

+ +

In CSS, these are the properties that apply to ::first-letter pseudo-elements: font properties, 'text-decoration', 'text-transform', 'letter-spacing', 'word-spacing' (when appropriate), 'line-height', 'float', 'vertical-align' (only if 'float' is 'none'), margin properties, padding properties, border properties, color property, background properties. UAs may apply other properties as well. To allow UAs to render a typographically correct drop cap or initial cap, the UA may choose a line-height, width and height based on the shape of the letter, unlike for normal elements.

+ +
+

Example:

+ +

This example shows a possible rendering of an initial cap. Note that the 'line-height' that is inherited by the ::first-letter pseudo-element is 1.1, but the UA in this example has computed the height of the first letter differently, so that it doesn't cause any unnecessary space between the first two lines. Also note that the fictional start tag of the first letter is inside the span, and thus the font weight of the first letter is normal, not bold as the span:

+
+p { line-height: 1.1 }
+p::first-letter { font-size: 3em; font-weight: normal }
+span { font-weight: bold }
+...
+<p><span>Het hemelsche</span> gerecht heeft zich ten lange lesten<br>
+Erbarremt over my en mijn benaeuwde vesten<br>
+En arme burgery, en op mijn volcx gebed<br>
+En dagelix geschrey de bange stad ontzet.
+
+ +
+

Image illustrating the ::first-letter pseudo-element

+
+
+ +
+

The following CSS will make a drop cap initial letter span about two lines:

+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<HTML>
+ <HEAD>
+  <TITLE>Drop cap initial letter</TITLE>
+  <STYLE type="text/css">
+   P               { font-size: 12pt; line-height: 1.2 }
+   P::first-letter { font-size: 200%; font-weight: bold; float: left }
+   SPAN            { text-transform: uppercase }
+  </STYLE>
+ </HEAD>
+ <BODY>
+  <P><SPAN>The first</SPAN> few words of an article
+    in The Economist.</P>
+ </BODY>
+</HTML>
+
+ +

This example might be formatted as follows:

+ +
+

Image illustrating the combined effect of the ::first-letter and ::first-line pseudo-elements

+
+ +

The fictional tag sequence is:

+
+<P>
+<SPAN>
+<P::first-letter>
+T
+</P::first-letter>he first
+</SPAN> 
+few words of an article in the Economist.
+</P>
+
+ +

Note that the ::first-letter pseudo-element tags abut the content (i.e., the initial character), while the ::first-line pseudo-element start tag is inserted right after the start tag of the block element.

+
+ +

In order to achieve traditional drop caps formatting, user agents may approximate font sizes, for example to align baselines. Also, the glyph outline may be taken into account when formatting.

+ +

Punctuation (i.e, characters defined in Unicode in the "open" (Ps), "close" (Pe), "initial" (Pi). "final" (Pf) and "other" (Po) punctuation classes), that precedes or follows the first letter should be included. [UNICODE]

+ +
+

Quotes that precede the first letter should be included.

+
+ +

The ::first-letter also applies if the first letter is in fact a digit, e.g., the "6" in "67 million dollars is a lot of money."

+ +

In CSS, the ::first-letter pseudo-element applies to block, list-item, table-cell, table-caption, and inline-block elements. A future version of this specification may allow this pesudo-element to apply to more element types.

+ +

The ::first-letter pseudo-element can be used with all such elements that contain text, or that have a descendant in the same flow that contains text. A UA should act as if the fictional start tag of the ::first-letter pseudo-element is just before the first text of the element, even if that first text is in a descendant.

+ +
+

Example:

+ +

The fictional tag sequence for this HTMLfragment:

+
+<div>
+<p>The first text.
+
+ +

is:

+
+<div>
+<p><div::first-letter><p::first-letter>T</...></...>he first text.
+
+
+ +

The first letter of a table-cell or inline-block cannot be the first letter of an ancestor element. Thus, in <DIV><P STYLE="display: inline-block">Hello<BR>Goodbye</P> etcetera</DIV> the first letter of the div is not the letter "H". In fact, the div doesn't have a first letter.

+ +

The first letter must occur on the first formatted line. For example, in this fragment: <p><br>First... the first line doesn't contain any letters and ::first-letter doesn't match anything (assuming the default style for br in HTML 4). In particular, it does not match the "F" of "First."

+ +

In CSS, if an element is a list item ('display: list-item'), the ::first-letter applies to the first letter in the principal box after the marker. UAs may ignore ::first-letter on list items with 'list-style-position: inside'. If an element has ::before or ::after content, the ::first-letter applies to the first letter of the element including that content.

+ +
+

Example:

+ +

After the rule 'p::before {content: "Note: "}', the selector 'p::first-letter' matches the "N" of "Note".

+
+ +

Some languages may have specific rules about how to treat certain letter combinations. In Dutch, for example, if the letter combination "ij" appears at the beginning of a word, both letters should be considered within the ::first-letter pseudo-element.

+ +

If the letters that would form the ::first-letter are not in the same element, such as "'T" in <p>'<em>T..., the UA may create a ::first-letter pseudo-element from one of the elements, both elements, or simply not create a pseudo-element.

+ +

Similarly, if the first letter(s) of the block are not at the start of the line (for example due to bidirectional reordering), then the UA need not create the pseudo-element(s).

+ +
+

Example:

+ +

The following example illustrates how overlapping pseudo-elements may interact. The first letter of each P element will be green with a font size of '24pt'. The rest of the first formatted line will be 'blue' while the rest of the paragraph will be 'red'.

+
+p { color: red; font-size: 12pt }
+p::first-letter { color: green; font-size: 200% }
+p::first-line { color: blue }
+
+<P>Some text that ends up on two lines</P>
+
+ +

Assuming that a line break will occur before the word "ends", the fictional tag sequence for this fragment might be:

+
+<P>
+<P::first-line>
+<P::first-letter> 
+S 
+</P::first-letter>ome text that 
+</P::first-line> 
+ends up on two lines 
+</P>
+
+ +

Note that the ::first-letter element is inside the ::first-line element. Properties set on ::first-line are inherited by ::first-letter, but are overridden if the same property is set on ::first-letter.

+
+ +

7.3. The ::selection pseudo-element

+ +

The ::selection pseudo-element applies to the portion of a document that has been highlighted by the user. This also applies, for example, to selected text within an editable text field. This pseudo-element should not be confused with the :checked pseudo-class (which used to be named :selected)

+ +

Although the ::selection pseudo-element is dynamic in nature, and is altered by user action, it is reasonable to expect that when a UA re-renders to a static medium (such as a printed page, see [CSS21]) which was originally rendered to a dynamic medium (like screen), the UA may wish to transfer the current ::selection state to that other medium, and have all the appropriate formatting and rendering take effect as well. This is not required — UAs may omit the ::selection pseudo-element for static media.

+ +

These are the CSS properties that apply to ::selection pseudo-elements: color, background, cursor (optional), outline (optional). The computed value of the 'background-image' property on ::selection may be ignored.

+ +

7.4. The ::before and ::after pseudo-elements

+ +

The ::before and ::after pseudo-elements can be used to describe generated content before or after an element's content. They are explained in CSS 2.1 [CSS21].

+ +

When the ::first-letter and ::first-line pseudo-elements are combined with ::before and ::after, they apply to the first letter or line of the element including the inserted text.

+ +

8. Combinators

+ +

8.1. Descendant combinator

+ +

At times, authors may want selectors to describe an element that is the descendant of another element in the document tree (e.g., "an EM element that is contained within an H1 element"). Descendant combinators express such a relationship. A descendant combinator is white space that separates two sequences of simple selectors. A selector of the form "A B" represents an element B that is an arbitrary descendant of some ancestor element A.

+ +
+

Examples:

+ +

For example, consider the following selector:

+
+h1 em
+
+ +

It represents an em element being the descendant of an h1 element. It is a correct and valid, but partial, description of the following fragment:

+
+<h1>This <span class="myclass">headline
+is <em>very</em> important</span></h1>
+
+ +

The following selector:

+
+div * p
+
+ +

represents a p element that is a grandchild or later descendant of a div element. Note the whitespace on either side of the "*" is not part of the universal selector; the whitespace is a combinator indicating that the DIV must be the ancestor of some element, and that that element must be an ancestor of the P.

+ +

The following selector, which combines descendant combinators and attribute selectors, represents an element that (1) has the href attribute set and (2) is inside a p that is itself inside a div:

+
+div p *[href]
+
+
+ +

8.2. Child combinators

+ +

A child combinator describes a childhood relationship between two elements. A child combinator is made of the "greater-than sign" (>) character and separates two sequences of simple selectors.

+ +
+

Examples:

+ +

The following selector represents a p element that is child of body:

+
+body > p
+
+ +

The following example combines descendant combinators and child combinators.

+
+div ol>li p
+
+ +

It represents a p element that is a descendant of an li element; the li element must be the child of an ol element; the ol element must be a descendant of a div. Notice that the optional white space around the ">" combinator has been left out.

+
+ +

For information on selecting the first child of an element, please see the section on the :first-child pseudo-class above.

+ +

8.3. Sibling combinators

+ +

There are two different sibling combinators: the adjacent sibling combinator and the general sibling combinator. In both cases, non-element nodes (e.g. text between elements) are ignored when considering adjacency of elements.

+ +

8.3.1. Adjacent sibling combinator

+ +

The adjacent sibling combinator is made of the "plus sign" (U+002B, +) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence immediately precedes the element represented by the second one.

+ +
+

Examples:

+ +

The following selector represents a p element immediately following a math element:

+
+math + p
+
+ +

The following selector is conceptually similar to the one in the previous example, except that it adds an attribute selector — it adds a constraint to the h1 element, that it must have class="opener":

+
+h1.opener + h2
+
+
+ +

8.3.2. General sibling combinator

+ +

The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.

+ +
+

Example:

+
+h1 ~ pre
+
+ +

represents a pre element following an h1. It is a correct and valid, but partial, description of:

+
+<h1>Definition of the function a</h1>
+<p>Function a(x) has to be applied to all figures in the table.</p>
+<pre>function a(x) = 12x/13.5</pre>
+
+
+ +

9. Calculating a selector's specificity

+ +

A selector's specificity is calculated as follows:

+ + + +

Selectors inside the negation pseudo-class are counted like any other, but the negation itself does not count as a pseudo-class.

+ +

Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity.

+ +
+

Examples:

+
+*               /* a=0 b=0 c=0 -> specificity =   0 */
+LI              /* a=0 b=0 c=1 -> specificity =   1 */
+UL LI           /* a=0 b=0 c=2 -> specificity =   2 */
+UL OL+LI        /* a=0 b=0 c=3 -> specificity =   3 */
+H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity =  11 */
+UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */
+LI.red.level    /* a=0 b=2 c=1 -> specificity =  21 */
+#x34y           /* a=1 b=0 c=0 -> specificity = 100 */
+#s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 101 */
+
+
+ +

Note: the specificity of the styles specified in an HTML style attribute is described in CSS 2.1. [CSS21].

+ +

10. The grammar of Selectors

+ +

10.1. Grammar

+ +

The grammar below defines the syntax of Selectors. It is globally LL(1) and can be locally LL(2) (but note that most UA's should not use it directly, since it doesn't express the parsing conventions). The format of the productions is optimized for human consumption and some shorthand notations beyond Yacc (see [YACC]) are used:

+ + + +

The productions are:

+
+selectors_group
+  : selector [ COMMA S* selector ]*
+  ;
+
+selector
+  : simple_selector_sequence [ combinator simple_selector_sequence ]*
+  ;
+
+combinator
+  /* combinators can be surrounded by white space */
+  : PLUS S* | GREATER S* | TILDE S* | S+
+  ;
+
+simple_selector_sequence
+  : [ type_selector | universal ]
+    [ HASH | class | attrib | pseudo | negation ]*
+  | [ HASH | class | attrib | pseudo | negation ]+
+  ;
+
+type_selector
+  : [ namespace_prefix ]? element_name
+  ;
+
+namespace_prefix
+  : [ IDENT | '*' ]? '|'
+  ;
+
+element_name
+  : IDENT
+  ;
+
+universal
+  : [ namespace_prefix ]? '*'
+  ;
+
+class
+  : '.' IDENT
+  ;
+
+attrib
+  : '[' S* [ namespace_prefix ]? IDENT S*
+        [ [ PREFIXMATCH |
+            SUFFIXMATCH |
+            SUBSTRINGMATCH |
+            '=' |
+            INCLUDES |
+            DASHMATCH ] S* [ IDENT | STRING ] S*
+        ]? ']'
+  ;
+
+pseudo
+  /* '::' starts a pseudo-element, ':' a pseudo-class */
+  /* Exceptions: :first-line, :first-letter, :before and :after. */
+  /* Note that pseudo-elements are restricted to one per selector and */
+  /* occur only in the last simple_selector_sequence. */
+  : ':' ':'? [ IDENT | functional_pseudo ]
+  ;
+
+functional_pseudo
+  : FUNCTION S* expression ')'
+  ;
+
+expression
+  /* In CSS3, the expressions are identifiers, strings, */
+  /* or of the form "an+b" */
+  : [ [ PLUS | '-' | DIMENSION | NUMBER | STRING | IDENT ] S* ]+
+  ;
+
+negation
+  : NOT S* negation_arg S* ')'
+  ;
+
+negation_arg
+  : type_selector | universal | HASH | class | attrib | pseudo
+  ;
+
+ +

10.2. Lexical scanner

+ +

The following is the tokenizer, written in Flex (see [FLEX]) notation. The tokenizer is case-insensitive.

+ +

The two occurrences of "\377" represent the highest character number that current versions of Flex can deal with (decimal 255). They should be read as "\4177777" (decimal 1114111), which is the highest possible code point in Unicode/ISO-10646. [UNICODE]

+
+%option case-insensitive
+
+ident     [-]?{nmstart}{nmchar}*
+name      {nmchar}+
+nmstart   [_a-z]|{nonascii}|{escape}
+nonascii  [^\0-\177]
+unicode   \\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?
+escape    {unicode}|\\[^\n\r\f0-9a-f]
+nmchar    [_a-z0-9-]|{nonascii}|{escape}
+num       [0-9]+|[0-9]*\.[0-9]+
+string    {string1}|{string2}
+string1   \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*\"
+string2   \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*\'
+invalid   {invalid1}|{invalid2}
+invalid1  \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*
+invalid2  \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*
+nl        \n|\r\n|\r|\f
+w         [ \t\r\n\f]*
+
+%%
+
+[ \t\r\n\f]+     return S;
+
+"~="             return INCLUDES;
+"|="             return DASHMATCH;
+"^="             return PREFIXMATCH;
+"$="             return SUFFIXMATCH;
+"*="             return SUBSTRINGMATCH;
+{ident}          return IDENT;
+{string}         return STRING;
+{ident}"("       return FUNCTION;
+{num}            return NUMBER;
+"#"{name}        return HASH;
+{w}"+"           return PLUS;
+{w}">"           return GREATER;
+{w}","           return COMMA;
+{w}"~"           return TILDE;
+":not("          return NOT;
+@{ident}         return ATKEYWORD;
+{invalid}        return INVALID;
+{num}%           return PERCENTAGE;
+{num}{ident}     return DIMENSION;
+"<!--"           return CDO;
+"-->"            return CDC;
+
+"url("{w}{string}{w}")"                           return URI;
+"url("{w}([!#$%&*-~]|{nonascii}|{escape})*{w}")"  return URI;
+U\+[0-9a-f?]{1,6}(-[0-9a-f]{1,6})?                return UNICODE_RANGE;
+
+\/\*[^*]*\*+([^/*][^*]*\*+)*\/                    /* ignore comments */
+
+.                return *yytext;
+
+ +

11. Namespaces and down-level clients

+ +

An important issue is the interaction of CSS selectors with XML documents in web clients that were produced prior to this document. Unfortunately, due to the fact that namespaces must be matched based on the URI which identifies the namespace, not the namespace prefix, some mechanism is required to identify namespaces in CSS by their URI as well. Without such a mechanism, it is impossible to construct a CSS style sheet which will properly match selectors in all cases against a random set of XML documents. However, given complete knowledge of the XML document to which a style sheet is to be applied, and a limited use of namespaces within the XML document, it is possible to construct a style sheet in which selectors would match elements and attributes correctly.

+ +

It should be noted that a down-level CSS client will (if it properly conforms to CSS forward compatible parsing rules) ignore all @namespace at-rules, as well as all style rules that make use of namespace qualified element type or attribute selectors. The syntax of delimiting namespace prefixes in CSS was deliberately chosen so that down-level CSS clients would ignore the style rules rather than possibly match them incorrectly.

+ +

The use of default namespaces in CSS makes it possible to write element type selectors that will function in both namespace aware CSS clients as well as down-level clients. It should be noted that down-level clients may incorrectly match selectors against XML elements in other namespaces.

+ +

The following are scenarios and examples in which it is possible to construct style sheets which would function properly in web clients that do not implement this proposal.

+ +
    +
  1. +

    The XML document does not use namespaces.

    + +
      +
    • In this case, it is obviously not necessary to declare or use namespaces in the style sheet. Standard CSS element type and attribute selectors will function adequately in a down-level client.
    • + +
    • In a CSS namespace aware client, the default behavior of element selectors matching without regard to namespace will function properly against all elements, since no namespaces are present. However, the use of specific element type selectors that match only elements that have no namespace ("|name") will guarantee that selectors will match only XML elements that do not have a declared namespace.
    • +
    +
  2. + +
  3. +

    The XML document defines a single, default namespace used throughout the document. No namespace prefixes are used in element names.

    + +
      +
    • In this case, a down-level client will function as if namespaces were not used in the XML document at all. Standard CSS element type and attribute selectors will match against all elements.
    • +
    +
  4. + +
  5. +

    The XML document does not use a default namespace, all namespace prefixes used are known to the style sheet author, and there is a direct mapping between namespace prefixes and namespace URIs. (A given prefix may only be mapped to one namespace URI throughout the XML document; there may be multiple prefixes mapped to the same URI).

    + +
      +
    • In this case, the down-level client will view and match element type and attribute selectors based on their fully qualified name, not the local part as outlined in the Type selectors and Namespaces section. CSS selectors may be declared using an escaped colon "\:" to describe the fully qualified names, e.g. "html\:h1" will match <html:h1>. Selectors using the qualified name will only match XML elements that use the same prefix. Other namespace prefixes used in the XML that are mapped to the same URI will not match as expected unless additional CSS style rules are declared for them.
    • + +
    • Note that selectors declared in this fashion will only match in down-level clients. A CSS namespace aware client will match element type and attribute selectors based on the name's local part. Selectors declared with the fully qualified name will not match (unless there is no namespace prefix in the fully qualified name).
    • +
    +
  6. +
+ +

In other scenarios: when the namespace prefixes used in the XML are not known in advance by the style sheet author; or a combination of elements with no namespace are used in conjunction with elements using a default namespace; or the same namespace prefix is mapped to different namespace URIs within the same document, or in different documents; it is impossible to construct a CSS style sheet that will function properly against all elements in those documents, unless, the style sheet is written using a namespace URI syntax (as outlined in this document or similar) and the document is processed by a CSS and XML namespace aware client.

+ +

12. Profiles

+ +

Each specification using Selectors must define the subset of W3C Selectors it allows and excludes, and describe the local meaning of all the components of that subset.

+ +

Non normative examples:

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Selectors profile
SpecificationCSS level 1
Acceptstype selectors
+ class selectors
+ ID selectors
+ :link, :visited and :active pseudo-classes
+ descendant combinator
+ ::first-line and ::first-letter pseudo-elements
Excludes +

universal selector
+ attribute selectors
+ :hover and :focus pseudo-classes
+ :target pseudo-class
+ :lang() pseudo-class
+ all UI element states pseudo-classes
+ all structural pseudo-classes
+ negation pseudo-class
+ all UI element fragments pseudo-elements
+ ::before and ::after pseudo-elements
+ child combinators
+ sibling combinators

+ +

namespaces

+
Extra constraintsonly one class selector allowed per sequence of simple selectors

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Selectors profile
SpecificationCSS level 2
Acceptstype selectors
+ universal selector
+ attribute presence and values selectors
+ class selectors
+ ID selectors
+ :link, :visited, :active, :hover, :focus, :lang() and :first-child pseudo-classes
+ descendant combinator
+ child combinator
+ adjacent sibling combinator
+ ::first-line and ::first-letter pseudo-elements
+ ::before and ::after pseudo-elements
Excludes +

content selectors
+ substring matching attribute selectors
+ :target pseudo-classes
+ all UI element states pseudo-classes
+ all structural pseudo-classes other than :first-child
+ negation pseudo-class
+ all UI element fragments pseudo-elements
+ general sibling combinators

+ +

namespaces

+
Extra constraintsmore than one class selector per sequence of simple selectors (CSS1 constraint) allowed
+ +

In CSS, selectors express pattern matching rules that determine which style rules apply to elements in the document tree.

+ +

The following selector (CSS level 2) will match all anchors a with attribute name set inside a section 1 header h1:

+
+h1 a[name]
+
+ +

All CSS declarations attached to such a selector are applied to elements matching it.

+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Selectors profile
SpecificationSTTS 3
Accepts +

type selectors
+ universal selectors
+ attribute selectors
+ class selectors
+ ID selectors
+ all structural pseudo-classes
+ all combinators

+ +

namespaces

+
Excludesnon-accepted pseudo-classes
+ pseudo-elements
Extra constraintssome selectors and combinators are not allowed in fragment descriptions on the right side of STTS declarations.
+ +

Selectors can be used in STTS 3 in two different manners:

+ +
    +
  1. a selection mechanism equivalent to CSS selection mechanism: declarations attached to a given selector are applied to elements matching that selector,
  2. + +
  3. fragment descriptions that appear on the right side of declarations.
  4. +
+
+ +

13. Conformance and requirements

+ +

This section defines conformance with the present specification only.

+ +

The inability of a user agent to implement part of this specification due to the limitations of a particular device (e.g., non interactive user agents will probably not implement dynamic pseudo-classes because they make no sense without interactivity) does not imply non-conformance.

+ +

All specifications reusing Selectors must contain a Profile listing the subset of Selectors it accepts or excludes, and describing the constraints it adds to the current specification.

+ +

Invalidity is caused by a parsing error, e.g. an unrecognized token or a token which is not allowed at the current parsing point.

+ +

User agents must observe the rules for handling parsing errors:

+ + + +

Specifications reusing Selectors must define how to handle parsing errors. (In the case of CSS, the entire rule in which the selector is used is dropped.)

+ +

14. Tests

+ +

This specification has a test suite allowing user agents to verify their basic conformance to the specification. This test suite does not pretend to be exhaustive and does not cover all possible combined cases of Selectors.

+ +

15. Acknowledgements

+ +

The CSS working group would like to thank everyone who has sent comments on this specification over the years.

+ +

The working group would like to extend special thanks to Donna McManus, Justin Baker, Joel Sklar, and Molly Ives Brower who perfermed the final editorial review.

+ +

16. References

+ +
+
[CSS1]
+ +
Bert Bos, Håkon Wium Lie; "Cascading Style Sheets, level 1", W3C Recommendation, 17 Dec 1996, revised 11 Jan 1999
+ +
(http://www.w3.org/TR/REC-CSS1)
+ +
[CSS21]
+ +
Bert Bos, Tantek Çelik, Ian Hickson, Håkon Wium Lie, editors; "Cascading Style Sheets, level 2 revision 1", W3C Working Draft, 13 June 2005
+ +
(http://www.w3.org/TR/CSS21)
+ +
[CWWW]
+ +
Martin J. Dürst, François Yergeau, Misha Wolf, Asmus Freytag, Tex Texin, editors; "Character Model for the World Wide Web", W3C Recommendation, 15 February 2005
+ +
(http://www.w3.org/TR/charmod/)
+ +
[FLEX]
+ +
"Flex: The Lexical Scanner Generator", Version 2.3.7, ISBN 1882114213
+ +
[HTML4]
+ +
Dave Ragget, Arnaud Le Hors, Ian Jacobs, editors; "HTML 4.01 Specification", W3C Recommendation, 24 December 1999
+ +
(http://www.w3.org/TR/html4/)
+ +
[MATH]
+ +
Patrick Ion, Robert Miner, editors; "Mathematical Markup Language (MathML) 1.01", W3C Recommendation, revision of 7 July 1999
+ +
(http://www.w3.org/TR/REC-MathML/)
+ +
[RFC3066]
+ +
H. Alvestrand; "Tags for the Identification of Languages", Request for Comments 3066, January 2001
+ +
(http://www.ietf.org/rfc/rfc3066.txt)
+ +
[STTS]
+ +
Daniel Glazman; "Simple Tree Transformation Sheets 3", Electricité de France, submission to the W3C, 11 November 1998
+ +
(http://www.w3.org/TR/NOTE-STTS3)
+ +
[SVG]
+ +
Jon Ferraiolo, 藤沢 淳, Dean Jackson, editors; "Scalable Vector Graphics (SVG) 1.1 Specification", W3C Recommendation, 14 January 2003
+ +
(http://www.w3.org/TR/SVG/)
+ +
[UNICODE]
+ +
The Unicode Standard, Version 4.1, The Unicode Consortium. Boston, MA, Addison-Wesley, March 2005. ISBN 0-321-18578-1, as amended by Unicode 4.0.1 and Unicode 4.1.0.
+ +
(http://www.unicode.org/versions/)
+ +
[XML10]
+ +
Tim Bray, Jean Paoli, C. M. Sperberg-McQueen, Eve Maler, François Yergeau, editors; "Extensible Markup Language (XML) 1.0 (Third Edition)", W3C Recommendation, 4 February 2004
+ +
(http://www.w3.org/TR/REC-xml/)
+ +
[XMLNAMES]
+ +
Tim Bray, Dave Hollander, Andrew Layman, editors; "Namespaces in XML", W3C Recommendation, 14 January 1999
+ +
(http://www.w3.org/TR/REC-xml-names/)
+ +
[YACC]
+ +
S. C. Johnson; "YACC — Yet another compiler compiler", Technical Report, Murray Hill, 1975
+
+ +
+ test +
+ +
+
+ test + +
+ test +
+ +
+
+ test +
+
+
+
+ +
+ d1d1 d2d2 d3d3 d4d4 d5d5 d6d6 +
+ +
+ d1 d1 d2 d2 d3 d3 d4 d4 d5 d5 d6 d6 +
+ + diff --git a/test_new/browser/fixtures/slick/template.xml b/test_new/browser/fixtures/slick/template.xml new file mode 100644 index 0000000..7d966fc --- /dev/null +++ b/test_new/browser/fixtures/slick/template.xml @@ -0,0 +1,2475 @@ + + + + + + + + template xhtml as xml + + + +
+

W3C

+ +

Selectors

+ +

W3C Working Draft 15 December 2005

+ +
+
This version:
+ +
http://www.w3.org/TR/2005/WD-css3-selectors-20051215
+ +
Latest version:
+ +
http://www.w3.org/TR/css3-selectors
+ +
Previous version:
+ +
http://www.w3.org/TR/2001/CR-css3-selectors-20011113
+ +
Editors:
+ +
Daniel Glazman (Invited Expert)
+ +
Tantek Çelik (Invited Expert)
+ +
Ian Hickson (Google)
+ +
Peter Linss (former editor, Netscape/AOL)
+ +
John Williams (former editor, Quark, Inc.)
+
+ + +
+
+ +

Abstract

+ +

Selectors are patterns that match against elements in a tree. Selectors have been optimized for use with HTML and XML, and are designed to be usable in performance-critical code.

+ +

CSS (Cascading Style Sheets) is a language for describing the rendering of HTML and XML documents on screen, on paper, in speech, etc. CSS uses Selectors for binding style properties to elements in the document. This document describes extensions to the selectors defined in CSS level 2. These extended selectors will be used by CSS level 3.

+ +

Selectors define the following function:

+
+expression ∗ element → boolean
+
+ +

That is, given an element and a selector, this specification defines whether that element matches the selector.

+ +

These expressions can also be used, for instance, to select a set of elements, or a single element from a set of elements, by evaluating the expression across all the elements in a subtree. STTS (Simple Tree Transformation Sheets), a language for transforming XML trees, uses this mechanism. [STTS]

+ +

Status of this document

+ +

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

+ +

This document describes the selectors that already exist in CSS1 and CSS2, and also proposes new selectors for CSS3 and other languages that may need them.

+ +

The CSS Working Group doesn't expect that all implementations of CSS3 will have to implement all selectors. Instead, there will probably be a small number of variants of CSS3, called profiles. For example, it may be that only a profile for interactive user agents will include all of the selectors.

+ +

This specification is a last call working draft for the the CSS Working Group (Style Activity). This document is a revision of the Candidate Recommendation dated 2001 November 13, and has incorporated implementation feedback received in the past few years. It is expected that this last call will proceed straight to Proposed Recommendation stage since it is believed that interoperability will be demonstrable.

+ +

All persons are encouraged to review and implement this specification and return comments to the (archived) public mailing list www-style (see instructions). W3C Members can also send comments directly to the CSS Working Group. The deadline for comments is 14 January 2006.

+ +

This is still a draft document and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to cite a W3C Working Draft as other than "work in progress".

+ +

This document may be available in translation. The English version of this specification is the only normative version.

+ +
+

Table of contents

+ + +
+ +

1. Introduction

+ +

1.1. Dependencies

+ +

Some features of this specification are specific to CSS, or have particular limitations or rules specific to CSS. In this specification, these have been described in terms of CSS2.1. [CSS21]

+ +

1.2. Terminology

+ +

All of the text of this specification is normative except examples, notes, and sections explicitly marked as non-normative.

+ +

1.3. Changes from CSS2

+ +

This section is non-normative.

+ +

The main differences between the selectors in CSS2 and those in Selectors are:

+ + + +

2. Selectors

+ +

This section is non-normative, as it merely summarizes the following sections.

+ +

A Selector represents a structure. This structure can be used as a condition (e.g. in a CSS rule) that determines which elements a selector matches in the document tree, or as a flat description of the HTML or XML fragment corresponding to that structure.

+ +

Selectors may range from simple element names to rich contextual representations.

+ +

The following table summarizes the Selector syntax:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PatternMeaningDescribed in sectionFirst defined in CSS level
*any elementUniversal selector2
Ean element of type EType selector1
E[foo]an E element with a "foo" attributeAttribute selectors2
E[foo="bar"]an E element whose "foo" attribute value is exactly equal to "bar"Attribute selectors2
E[foo~="bar"]an E element whose "foo" attribute value is a list of space-separated values, one of which is exactly equal to "bar"Attribute selectors2
E[foo^="bar"]an E element whose "foo" attribute value begins exactly with the string "bar"Attribute selectors3
E[foo$="bar"]an E element whose "foo" attribute value ends exactly with the string "bar"Attribute selectors3
E[foo*="bar"]an E element whose "foo" attribute value contains the substring "bar"Attribute selectors3
E[hreflang|="en"]an E element whose "hreflang" attribute has a hyphen-separated list of values beginning (from the left) with "en"Attribute selectors2
E:rootan E element, root of the documentStructural pseudo-classes3
E:nth-child(n)an E element, the n-th child of its parentStructural pseudo-classes3
E:nth-last-child(n)an E element, the n-th child of its parent, counting from the last oneStructural pseudo-classes3
E:nth-of-type(n)an E element, the n-th sibling of its typeStructural pseudo-classes3
E:nth-last-of-type(n)an E element, the n-th sibling of its type, counting from the last oneStructural pseudo-classes3
E:first-childan E element, first child of its parentStructural pseudo-classes2
E:last-childan E element, last child of its parentStructural pseudo-classes3
E:first-of-typean E element, first sibling of its typeStructural pseudo-classes3
E:last-of-typean E element, last sibling of its typeStructural pseudo-classes3
E:only-childan E element, only child of its parentStructural pseudo-classes3
E:only-of-typean E element, only sibling of its typeStructural pseudo-classes3
E:emptyan E element that has no children (including text nodes)Structural pseudo-classes3
E:link
+ E:visited
an E element being the source anchor of a hyperlink of which the target is not yet visited (:link) or already visited (:visited)The link pseudo-classes1
E:active
+ E:hover
+ E:focus
an E element during certain user actionsThe user action pseudo-classes1 and 2
E:targetan E element being the target of the referring URIThe target pseudo-class3
E:lang(fr)an element of type E in language "fr" (the document language specifies how language is determined)The :lang() pseudo-class2
E:enabled
+ E:disabled
a user interface element E which is enabled or disabledThe UI element states pseudo-classes3
E:checkeda user interface element E which is checked (for instance a radio-button or checkbox)The UI element states pseudo-classes3
E::first-linethe first formatted line of an E elementThe ::first-line pseudo-element1
E::first-letterthe first formatted letter of an E elementThe ::first-letter pseudo-element1
E::selectionthe portion of an E element that is currently selected/highlighted by the userThe UI element fragments pseudo-elements3
E::beforegenerated content before an E elementThe ::before pseudo-element2
E::aftergenerated content after an E elementThe ::after pseudo-element2
E.warningan E element whose class is "warning" (the document language specifies how class is determined).Class selectors1
E#myidan E element with ID equal to "myid".ID selectors1
E:not(s)an E element that does not match simple selector sNegation pseudo-class3
E Fan F element descendant of an E elementDescendant combinator1
E > Fan F element child of an E elementChild combinator2
E + Fan F element immediately preceded by an E elementAdjacent sibling combinator2
E ~ Fan F element preceded by an E elementGeneral sibling combinator3
+ +

The meaning of each selector is derived from the table above by prepending "matches" to the contents of each cell in the "Meaning" column.

+ +

3. Case sensitivity

+ +

The case sensitivity of document language element names, attribute names, and attribute values in selectors depends on the document language. For example, in HTML, element names are case-insensitive, but in XML, they are case-sensitive.

+ +

4. Selector syntax

+ +

A selector is a chain of one or more sequences of simple selectors separated by combinators.

+ +

A sequence of simple selectors is a chain of simple selectors that are not separated by a combinator. It always begins with a type selector or a universal selector. No other type selector or universal selector is allowed in the sequence.

+ +

A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, content selector, or pseudo-class. One pseudo-element may be appended to the last sequence of simple selectors.

+ +

Combinators are: white space, "greater-than sign" (U+003E, >), "plus sign" (U+002B, +) and "tilde" (U+007E, ~). White space may appear between a combinator and the simple selectors around it. Only the characters "space" (U+0020), "tab" (U+0009), "line feed" (U+000A), "carriage return" (U+000D), and "form feed" (U+000C) can occur in white space. Other space-like characters, such as "em-space" (U+2003) and "ideographic space" (U+3000), are never part of white space.

+ +

The elements of a document tree that are represented by a selector are the subjects of the selector. A selector consisting of a single sequence of simple selectors represents any element satisfying its requirements. Prepending another sequence of simple selectors and a combinator to a sequence imposes additional matching constraints, so the subjects of a selector are always a subset of the elements represented by the last sequence of simple selectors.

+ +

An empty selector, containing no sequence of simple selectors and no pseudo-element, is an invalid selector.

+ +

5. Groups of selectors

+ +

When several selectors share the same declarations, they may be grouped into a comma-separated list. (A comma is U+002C.)

+ +
+

CSS examples:

+ +

In this example, we condense three rules with identical declarations into one. Thus,

+
+h1 { font-family: sans-serif }
+h2 { font-family: sans-serif }
+h3 { font-family: sans-serif }
+
+ +

is equivalent to:

+
+h1, h2, h3 { font-family: sans-serif }
+
+
+ +

Warning: the equivalence is true in this example because all the selectors are valid selectors. If just one of these selectors were invalid, the entire group of selectors would be invalid. This would invalidate the rule for all three heading elements, whereas in the former case only one of the three individual heading rules would be invalidated.

+ +

6. Simple selectors

+ +

6.1. Type selector

+ +

A type selector is the name of a document language element type. A type selector represents an instance of the element type in the document tree.

+ +
+

Example:

+ +

The following selector represents an h1 element in the document tree:

+
+h1
+
+
+ +

6.1.1. Type selectors and namespaces

+ +

Type selectors allow an optional namespace ([XMLNAMES]) component. A namespace prefix that has been previously declared may be prepended to the element name separated by the namespace separator "vertical bar" (U+007C, |).

+ +

The namespace component may be left empty to indicate that the selector is only to represent elements with no declared namespace.

+ +

An asterisk may be used for the namespace prefix, indicating that the selector represents elements in any namespace (including elements with no namespace).

+ +

Element type selectors that have no namespace component (no namespace separator), represent elements without regard to the element's namespace (equivalent to "*|") unless a default namespace has been declared. If a default namespace has been declared, the selector will represent only elements in the default namespace.

+ +

A type selector containing a namespace prefix that has not been previously declared is an invalid selector. The mechanism for declaring a namespace prefix is left up to the language implementing Selectors. In CSS, such a mechanism is defined in the General Syntax module.

+ +

In a namespace-aware client, element type selectors will only match against the local part of the element's qualified name. See below for notes about matching behaviors in down-level clients.

+ +

In summary:

+ +
+
ns|E
+ +
elements with name E in namespace ns
+ +
*|E
+ +
elements with name E in any namespace, including those without any declared namespace
+ +
|E
+ +
elements with name E without any declared namespace
+ +
E
+ +
if no default namespace has been specified, this is equivalent to *|E. Otherwise it is equivalent to ns|E where ns is the default namespace.
+
+ +
+

CSS examples:

+
+@namespace foo url(http://www.example.com);
+ foo|h1 { color: blue }
+ foo|* { color: yellow }
+ |h1 { color: red }
+ *|h1 { color: green }
+ h1 { color: green }
+
+ +

The first rule will match only h1 elements in the "http://www.example.com" namespace.

+ +

The second rule will match all elements in the "http://www.example.com" namespace.

+ +

The third rule will match only h1 elements without any declared namespace.

+ +

The fourth rule will match h1 elements in any namespace (including those without any declared namespace).

+ +

The last rule is equivalent to the fourth rule because no default namespace has been defined.

+
+ +

6.2. Universal selector

+ +

The universal selector, written "asterisk" (*), represents the qualified name of any element type. It represents any single element in the document tree in any namespace (including those without any declared namespace) if no default namespace has been specified. If a default namespace has been specified, see Universal selector and Namespaces below.

+ +

If the universal selector is not the only component of a sequence of simple selectors, the * may be omitted.

+ +
+

Examples:

+ +
    +
  • *[hreflang|=en] and [hreflang|=en] are equivalent,
  • + +
  • *.warning and .warning are equivalent,
  • + +
  • *#myid and #myid are equivalent.
  • +
+
+ +

Note: it is recommended that the *, representing the universal selector, not be omitted.

+ +

6.2.1. Universal selector and namespaces

+ +

The universal selector allows an optional namespace component. It is used as follows:

+ +
+
ns|*
+ +
all elements in namespace ns
+ +
*|*
+ +
all elements
+ +
|*
+ +
all elements without any declared namespace
+ +
*
+ +
if no default namespace has been specified, this is equivalent to *|*. Otherwise it is equivalent to ns|* where ns is the default namespace.
+
+ +

A universal selector containing a namespace prefix that has not been previously declared is an invalid selector. The mechanism for declaring a namespace prefix is left up to the language implementing Selectors. In CSS, such a mechanism is defined in the General Syntax module.

+ +

6.3. Attribute selectors

+ +

Selectors allow the representation of an element's attributes. When a selector is used as an expression to match against an element, attribute selectors must be considered to match an element if that element has an attribute that matches the attribute represented by the attribute selector.

+ +

6.3.1. Attribute presence and values selectors

+ +

CSS2 introduced four attribute selectors:

+ +
+
[att]
+ +
Represents an element with the att attribute, whatever the value of the attribute.
+ +
[att=val]
+ +
Represents an element with the att attribute whose value is exactly "val".
+ +
[att~=val]
+ +
Represents an element with the att attribute whose value is a whitespace-separated list of words, one of which is exactly "val". If "val" contains whitespace, it will never represent anything (since the words are separated by spaces).
+ +
[att|=val]
+ +
Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D). This is primarily intended to allow language subcode matches (e.g., the hreflang attribute on the link element in HTML) as described in RFC 3066 ([RFC3066]). For lang (or xml:lang) language subcode matching, please see the :lang pseudo-class.
+
+ +

Attribute values must be identifiers or strings. The case-sensitivity of attribute names and values in selectors depends on the document language.

+ +
+

Examples:

+ +

The following attribute selector represents an h1 element that carries the title attribute, whatever its value:

+
+h1[title]
+
+ +

In the following example, the selector represents a span element whose class attribute has exactly the value "example":

+
+span[class="example"]
+
+ +

Multiple attribute selectors can be used to represent several attributes of an element, or several conditions on the same attribute. Here, the selector represents a span element whose hello attribute has exactly the value "Cleveland" and whose goodbye attribute has exactly the value "Columbus":

+
+span[hello="Cleveland"][goodbye="Columbus"]
+
+ +

The following selectors illustrate the differences between "=" and "~=". The first selector will represent, for example, the value "copyright copyleft copyeditor" on a rel attribute. The second selector will only represent an a element with an href attribute having the exact value "http://www.w3.org/".

+
+a[rel~="copyright"]
+a[href="http://www.w3.org/"]
+
+ +

The following selector represents a link element whose hreflang attribute is exactly "fr".

+
+link[hreflang=fr]
+
+ +

The following selector represents a link element for which the values of the hreflang attribute begins with "en", including "en", "en-US", and "en-cockney":

+
+link[hreflang|="en"]
+
+ +

Similarly, the following selectors represents a DIALOGUE element whenever it has one of two different values for an attribute character:

+
+DIALOGUE[character=romeo]
+DIALOGUE[character=juliet]
+
+
+ +

6.3.2. Substring matching attribute selectors

+ +

Three additional attribute selectors are provided for matching substrings in the value of an attribute:

+ +
+
[att^=val]
+ +
Represents an element with the att attribute whose value begins with the prefix "val".
+ +
[att$=val]
+ +
Represents an element with the att attribute whose value ends with the suffix "val".
+ +
[att*=val]
+ +
Represents an element with the att attribute whose value contains at least one instance of the substring "val".
+
+ +

Attribute values must be identifiers or strings. The case-sensitivity of attribute names in selectors depends on the document language.

+ +
+

Examples:

+ +

The following selector represents an HTML object, referencing an image:

+
+object[type^="image/"]
+
+ +

The following selector represents an HTML anchor a with an href attribute whose value ends with ".html".

+
+a[href$=".html"]
+
+ +

The following selector represents an HTML paragraph with a title attribute whose value contains the substring "hello"

+
+p[title*="hello"]
+
+
+ +

6.3.3. Attribute selectors and namespaces

+ +

Attribute selectors allow an optional namespace component to the attribute name. A namespace prefix that has been previously declared may be prepended to the attribute name separated by the namespace separator "vertical bar" (|). In keeping with the Namespaces in the XML recommendation, default namespaces do not apply to attributes, therefore attribute selectors without a namespace component apply only to attributes that have no declared namespace (equivalent to "|attr"). An asterisk may be used for the namespace prefix indicating that the selector is to match all attribute names without regard to the attribute's namespace.

+ +

An attribute selector with an attribute name containing a namespace prefix that has not been previously declared is an invalid selector. The mechanism for declaring a namespace prefix is left up to the language implementing Selectors. In CSS, such a mechanism is defined in the General Syntax module.

+ +
+

CSS examples:

+
+@namespace foo "http://www.example.com";
+[foo|att=val] { color: blue }
+[*|att] { color: yellow }
+[|att] { color: green }
+[att] { color: green }
+
+ +

The first rule will match only elements with the attribute att in the "http://www.example.com" namespace with the value "val".

+ +

The second rule will match only elements with the attribute att regardless of the namespace of the attribute (including no declared namespace).

+ +

The last two rules are equivalent and will match only elements with the attribute att where the attribute is not declared to be in a namespace.

+
+ +

6.3.4. Default attribute values in DTDs

+ +

Attribute selectors represent explicitly set attribute values in the document tree. Default attribute values may be defined in a DTD or elsewhere, but cannot always be selected by attribute selectors. Selectors should be designed so that they work even if the default values are not included in the document tree.

+ +

More precisely, a UA is not required to read an "external subset" of the DTD but is required to look for default attribute values in the document's "internal subset." (See [XML10] for definitions of these subsets.)

+ +

A UA that recognizes an XML namespace [XMLNAMES] is not required to use its knowledge of that namespace to treat default attribute values as if they were present in the document. (For example, an XHTML UA is not required to use its built-in knowledge of the XHTML DTD.)

+ +

Note: Typically, implementations choose to ignore external subsets.

+ +
+

Example:

+ +

Consider an element EXAMPLE with an attribute "notation" that has a default value of "decimal". The DTD fragment might be

+
+<!ATTLIST EXAMPLE notation (decimal,octal) "decimal">
+
+ +

If the style sheet contains the rules

+
+EXAMPLE[notation=decimal] { /*... default property settings ...*/ }
+EXAMPLE[notation=octal]   { /*... other settings...*/ }
+
+ +

the first rule will not match elements whose "notation" attribute is set by default, i.e. not set explicitly. To catch all cases, the attribute selector for the default value must be dropped:

+
+EXAMPLE                   { /*... default property settings ...*/ }
+EXAMPLE[notation=octal]   { /*... other settings...*/ }
+
+ +

Here, because the selector EXAMPLE[notation=octal] is more specific than the tag selector alone, the style declarations in the second rule will override those in the first for elements that have a "notation" attribute value of "octal". Care has to be taken that all property declarations that are to apply only to the default case are overridden in the non-default cases' style rules.

+
+ +

6.4. Class selectors

+ +

Working with HTML, authors may use the period (U+002E, .) notation as an alternative to the ~= notation when representing the class attribute. Thus, for HTML, div.value and div[class~=value] have the same meaning. The attribute value must immediately follow the "period" (.).

+ +

UAs may apply selectors using the period (.) notation in XML documents if the UA has namespace-specific knowledge that allows it to determine which attribute is the "class" attribute for the respective namespace. One such example of namespace-specific knowledge is the prose in the specification for a particular namespace (e.g. SVG 1.0 [SVG] describes the SVG "class" attribute and how a UA should interpret it, and similarly MathML 1.01 [MATH] describes the MathML "class" attribute.)

+ +
+

CSS examples:

+ +

We can assign style information to all elements with class~="pastoral" as follows:

+
+*.pastoral { color: green }  /* all elements with class~=pastoral */
+
+ +

or just

+
+.pastoral { color: green }  /* all elements with class~=pastoral */
+
+ +

The following assigns style only to H1 elements with class~="pastoral":

+
+H1.pastoral { color: green }  /* H1 elements with class~=pastoral */
+
+ +

Given these rules, the first H1 instance below would not have green text, while the second would:

+
+<H1>Not green</H1>
+<H1 class="pastoral">Very green</H1>
+
+
+ +

To represent a subset of "class" values, each value must be preceded by a ".", in any order.

+ +
+

CSS example:

+ +

The following rule matches any P element whose "class" attribute has been assigned a list of whitespace-separated values that includes "pastoral" and "marine":

+
+p.pastoral.marine { color: green }
+
+ +

This rule matches when class="pastoral blue aqua marine" but does not match for class="pastoral blue".

+
+ +

Note: Because CSS gives considerable power to the "class" attribute, authors could conceivably design their own "document language" based on elements with almost no associated presentation (such as DIV and SPAN in HTML) and assigning style information through the "class" attribute. Authors should avoid this practice since the structural elements of a document language often have recognized and accepted meanings and author-defined classes may not.

+ +

Note: If an element has multiple class attributes, their values must be concatenated with spaces between the values before searching for the class. As of this time the working group is not aware of any manner in which this situation can be reached, however, so this behavior is explicitly non-normative in this specification.

+ +

6.5. ID selectors

+ +

Document languages may contain attributes that are declared to be of type ID. What makes attributes of type ID special is that no two such attributes can have the same value in a document, regardless of the type of the elements that carry them; whatever the document language, an ID typed attribute can be used to uniquely identify its element. In HTML all ID attributes are named "id"; XML applications may name ID attributes differently, but the same restriction applies.

+ +

An ID-typed attribute of a document language allows authors to assign an identifier to one element instance in the document tree. W3C ID selectors represent an element instance based on its identifier. An ID selector contains a "number sign" (U+0023, #) immediately followed by the ID value, which must be an identifier.

+ +

Selectors does not specify how a UA knows the ID-typed attribute of an element. The UA may, e.g., read a document's DTD, have the information hard-coded or ask the user.

+ +
+

Examples:

+ +

The following ID selector represents an h1 element whose ID-typed attribute has the value "chapter1":

+
+h1#chapter1
+
+ +

The following ID selector represents any element whose ID-typed attribute has the value "chapter1":

+
+#chapter1
+
+ +

The following selector represents any element whose ID-typed attribute has the value "z98y".

+
+*#z98y
+
+
+ +

Note. In XML 1.0 [XML10], the information about which attribute contains an element's IDs is contained in a DTD or a schema. When parsing XML, UAs do not always read the DTD, and thus may not know what the ID of an element is (though a UA may have namespace-specific knowledge that allows it to determine which attribute is the ID attribute for that namespace). If a style sheet designer knows or suspects that a UA may not know what the ID of an element is, he should use normal attribute selectors instead: [name=p371] instead of #p371. Elements in XML 1.0 documents without a DTD do not have IDs at all.

+ +

If an element has multiple ID attributes, all of them must be treated as IDs for that element for the purposes of the ID selector. Such a situation could be reached using mixtures of xml:id, DOM3 Core, XML DTDs, and namespace-specific knowledge.

+ +

6.6. Pseudo-classes

+ +

The pseudo-class concept is introduced to permit selection based on information that lies outside of the document tree or that cannot be expressed using the other simple selectors.

+ +

A pseudo-class always consists of a "colon" (:) followed by the name of the pseudo-class and optionally by a value between parentheses.

+ +

Pseudo-classes are allowed in all sequences of simple selectors contained in a selector. Pseudo-classes are allowed anywhere in sequences of simple selectors, after the leading type selector or universal selector (possibly omitted). Pseudo-class names are case-insensitive. Some pseudo-classes are mutually exclusive, while others can be applied simultaneously to the same element. Pseudo-classes may be dynamic, in the sense that an element may acquire or lose a pseudo-class while a user interacts with the document.

+ +

6.6.1. Dynamic pseudo-classes

+ +

Dynamic pseudo-classes classify elements on characteristics other than their name, attributes, or content, in principle characteristics that cannot be deduced from the document tree.

+ +

Dynamic pseudo-classes do not appear in the document source or document tree.

+ +
The link pseudo-classes: :link and :visited
+ +

User agents commonly display unvisited links differently from previously visited ones. Selectors provides the pseudo-classes :link and :visited to distinguish them:

+ + + +

After some amount of time, user agents may choose to return a visited link to the (unvisited) ':link' state.

+ +

The two states are mutually exclusive.

+ +
+

Example:

+ +

The following selector represents links carrying class external and already visited:

+
+a.external:visited
+
+
+ +

Note: It is possible for style sheet authors to abuse the :link and :visited pseudo-classes to determine which sites a user has visited without the user's consent.

+ +

UAs may therefore treat all links as unvisited links, or implement other measures to preserve the user's privacy while rendering visited and unvisited links differently.

+ +
The user action pseudo-classes :hover, :active, and :focus
+ +

Interactive user agents sometimes change the rendering in response to user actions. Selectors provides three pseudo-classes for the selection of an element the user is acting on.

+ + + +

There may be document language or implementation specific limits on which elements can become :active or acquire :focus.

+ +

These pseudo-classes are not mutually exclusive. An element may match several pseudo-classes at the same time.

+ +

Selectors doesn't define if the parent of an element that is ':active' or ':hover' is also in that state.

+ +
+

Examples:

+
+a:link    /* unvisited links */
+a:visited /* visited links */
+a:hover   /* user hovers */
+a:active  /* active links */
+
+ +

An example of combining dynamic pseudo-classes:

+
+a:focus
+a:focus:hover
+
+ +

The last selector matches a elements that are in the pseudo-class :focus and in the pseudo-class :hover.

+
+ +

Note: An element can be both ':visited' and ':active' (or ':link' and ':active').

+ +

6.6.2. The target pseudo-class :target

+ +

Some URIs refer to a location within a resource. This kind of URI ends with a "number sign" (#) followed by an anchor identifier (called the fragment identifier).

+ +

URIs with fragment identifiers link to a certain element within the document, known as the target element. For instance, here is a URI pointing to an anchor named section_2 in an HTML document:

+
+http://example.com/html/top.html#section_2
+
+ +

A target element can be represented by the :target pseudo-class. If the document's URI has no fragment identifier, then the document has no target element.

+ +
+

Example:

+
+p.note:target
+
+ +

This selector represents a p element of class note that is the target element of the referring URI.

+
+ +
+

CSS example:

+ +

Here, the :target pseudo-class is used to make the target element red and place an image before it, if there is one:

+
+*:target { color : red }
+*:target::before { content : url(target.png) }
+
+
+ +

6.6.3. The language pseudo-class :lang

+ +

If the document language specifies how the human language of an element is determined, it is possible to write selectors that represent an element based on its language. For example, in HTML [HTML4], the language is determined by a combination of the lang attribute, the meta element, and possibly by information from the protocol (such as HTTP headers). XML uses an attribute called xml:lang, and there may be other document language-specific methods for determining the language.

+ +

The pseudo-class :lang(C) represents an element that is in language C. Whether an element is represented by a :lang() selector is based solely on the identifier C being either equal to, or a hyphen-separated substring of, the element's language value, in the same way as if performed by the '|=' operator in attribute selectors. The identifier C does not have to be a valid language name.

+ +

C must not be empty. (If it is, the selector is invalid.)

+ +

Note: It is recommended that documents and protocols indicate language using codes from RFC 3066 [RFC3066] or its successor, and by means of "xml:lang" attributes in the case of XML-based documents [XML10]. See "FAQ: Two-letter or three-letter language codes."

+ +
+

Examples:

+ +

The two following selectors represent an HTML document that is in Belgian, French, or German. The two next selectors represent q quotations in an arbitrary element in Belgian, French, or German.

+
+html:lang(fr-be)
+html:lang(de)
+:lang(fr-be) > q
+:lang(de) > q
+
+
+ +

6.6.4. The UI element states pseudo-classes

+ +
The :enabled and :disabled pseudo-classes
+ +

The :enabled pseudo-class allows authors to customize the look of user interface elements that are enabled — which the user can select or activate in some fashion (e.g. clicking on a button with a mouse). There is a need for such a pseudo-class because there is no way to programmatically specify the default appearance of say, an enabled input element without also specifying what it would look like when it was disabled.

+ +

Similar to :enabled, :disabled allows the author to specify precisely how a disabled or inactive user interface element should look.

+ +

Most elements will be neither enabled nor disabled. An element is enabled if the user can either activate it or transfer the focus to it. An element is disabled if it could be enabled, but the user cannot presently activate it or transfer focus to it.

+ +
The :checked pseudo-class
+ +

Radio and checkbox elements can be toggled by the user. Some menu items are "checked" when the user selects them. When such elements are toggled "on" the :checked pseudo-class applies. The :checked pseudo-class initially applies to such elements that have the HTML4 selected and checked attributes as described in Section 17.2.1 of HTML4, but of course the user can toggle "off" such elements in which case the :checked pseudo-class would no longer apply. While the :checked pseudo-class is dynamic in nature, and is altered by user action, since it can also be based on the presence of the semantic HTML4 selected and checked attributes, it applies to all media.

+ +
The :indeterminate pseudo-class
+ +
+

Radio and checkbox elements can be toggled by the user, but are sometimes in an indeterminate state, neither checked nor unchecked. This can be due to an element attribute, or DOM manipulation.

+ +

A future version of this specification may introduce an :indeterminate pseudo-class that applies to such elements.

+
+ +

6.6.5. Structural pseudo-classes

+ +

Selectors introduces the concept of structural pseudo-classes to permit selection based on extra information that lies in the document tree but cannot be represented by other simple selectors or combinators.

+ +

Note that standalone pieces of PCDATA (text nodes in the DOM) are not counted when calculating the position of an element in the list of children of its parent. When calculating the position of an element in the list of children of its parent, the index numbering starts at 1.

+ +
:root pseudo-class
+ +

The :root pseudo-class represents an element that is the root of the document. In HTML 4, this is always the HTML element.

+ +
:nth-child() pseudo-class
+ +

The :nth-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree, for a given positive integer or zero value of n, and has a parent element. In other words, this matches the bth child of an element after all the children have been split into groups of a elements each. For example, this allows the selectors to address every other row in a table, and could be used to alternate the color of paragraph text in a cycle of four. The a and b values must be zero, negative integers or positive integers. The index of the first child of an element is 1.

+ +

In addition to this, :nth-child() can take 'odd' and 'even' as arguments instead. 'odd' has the same signification as 2n+1, and 'even' has the same signification as 2n.

+ +
+

Examples:

+
+tr:nth-child(2n+1) /* represents every odd row of an HTML table */
+tr:nth-child(odd)  /* same */
+tr:nth-child(2n)   /* represents every even row of an HTML table */
+tr:nth-child(even) /* same */
+
+/* Alternate paragraph colours in CSS */
+p:nth-child(4n+1) { color: navy; }
+p:nth-child(4n+2) { color: green; }
+p:nth-child(4n+3) { color: maroon; }
+p:nth-child(4n+4) { color: purple; }
+
+
+ +

When a=0, no repeating is used, so for example :nth-child(0n+5) matches only the fifth child. When a=0, the an part need not be included, so the syntax simplifies to :nth-child(b) and the last example simplifies to :nth-child(5).

+ +
+

Examples:

+
+foo:nth-child(0n+1)   /* represents an element foo, first child of its parent element */
+foo:nth-child(1)      /* same */
+
+
+ +

When a=1, the number may be omitted from the rule.

+ +
+

Examples:

+ +

The following selectors are therefore equivalent:

+
+bar:nth-child(1n+0)   /* represents all bar elements, specificity (0,1,1) */
+bar:nth-child(n+0)    /* same */
+bar:nth-child(n)      /* same */
+bar                   /* same but lower specificity (0,0,1) */
+
+
+ +

If b=0, then every ath element is picked. In such a case, the b part may be omitted.

+ +
+

Examples:

+
+tr:nth-child(2n+0) /* represents every even row of an HTML table */
+tr:nth-child(2n) /* same */
+
+
+ +

If both a and b are equal to zero, the pseudo-class represents no element in the document tree.

+ +

The value a can be negative, but only the positive values of an+b, for n≥0, may represent an element in the document tree.

+ +
+

Example:

+
+html|tr:nth-child(-n+6)  /* represents the 6 first rows of XHTML tables */
+
+
+ +

When the value b is negative, the "+" character in the expression must be removed (it is effectively replaced by the "-" character indicating the negative value of b).

+ +
+

Examples:

+
+:nth-child(10n-1)  /* represents the 9th, 19th, 29th, etc, element */
+:nth-child(10n+9)  /* Same */
+:nth-child(10n+-1) /* Syntactically invalid, and would be ignored */
+
+
+ +
:nth-last-child() pseudo-class
+ +

The :nth-last-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings after it in the document tree, for a given positive integer or zero value of n, and has a parent element. See :nth-child() pseudo-class for the syntax of its argument. It also accepts the 'even' and 'odd' values as arguments.

+ +
+

Examples:

+
+tr:nth-last-child(-n+2)    /* represents the two last rows of an HTML table */
+
+foo:nth-last-child(odd)    /* represents all odd foo elements in their parent element,
+                              counting from the last one */
+
+
+ +
:nth-of-type() pseudo-class
+ +

The :nth-of-type(an+b) pseudo-class notation represents an element that has an+b-1 siblings with the same element name before it in the document tree, for a given zero or positive integer value of n, and has a parent element. In other words, this matches the bth child of that type after all the children of that type have been split into groups of a elements each. See :nth-child() pseudo-class for the syntax of its argument. It also accepts the 'even' and 'odd' values.

+ +
+

CSS example:

+ +

This allows an author to alternate the position of floated images:

+
+img:nth-of-type(2n+1) { float: right; }
+img:nth-of-type(2n) { float: left; }
+
+
+ +
:nth-last-of-type() pseudo-class
+ +

The :nth-last-of-type(an+b) pseudo-class notation represents an element that has an+b-1 siblings with the same element name after it in the document tree, for a given zero or positive integer value of n, and has a parent element. See :nth-child() pseudo-class for the syntax of its argument. It also accepts the 'even' and 'odd' values.

+ +
+

Example:

+ +

To represent all h2 children of an XHTML body except the first and last, one could use the following selector:

+
+body > h2:nth-of-type(n+2):nth-last-of-type(n+2)
+
+ +

In this case, one could also use :not(), although the selector ends up being just as long:

+
+body > h2:not(:first-of-type):not(:last-of-type)
+
+
+ +
:first-child pseudo-class
+ +

Same as :nth-child(1). The :first-child pseudo-class represents an element that is the first child of some other element.

+ +
+

Examples:

+ +

The following selector represents a p element that is the first child of a div element:

+
+div > p:first-child
+
+ +

This selector can represent the p inside the div of the following fragment:

+
+<p> The last P before the note.</p>
+<div class="note">
+   <p> The first P inside the note.</p>
+</div>
+
but cannot represent the second p in the following fragment: +
+<p> The last P before the note.</p>
+<div class="note">
+   <h2> Note </h2>
+   <p> The first P inside the note.</p>
+</div>
+
+ +

The following two selectors are usually equivalent:

+
+* > a:first-child /* a is first child of any element */
+a:first-child /* Same (assuming a is not the root element) */
+
+
+ +
:last-child pseudo-class
+ +

Same as :nth-last-child(1). The :last-child pseudo-class represents an element that is the last child of some other element.

+ +
+

Example:

+ +

The following selector represents a list item li that is the last child of an ordered list ol.

+
+ol > li:last-child
+
+
+ +
:first-of-type pseudo-class
+ +

Same as :nth-of-type(1). The :first-of-type pseudo-class represents an element that is the first sibling of its type in the list of children of its parent element.

+ +
+

Example:

+ +

The following selector represents a definition title dt inside a definition list dl, this dt being the first of its type in the list of children of its parent element.

+
+dl dt:first-of-type
+
+ +

It is a valid description for the first two dt elements in the following example but not for the third one:

+
+<dl>
+ <dt>gigogne</dt>
+ <dd>
+  <dl>
+   <dt>fusée</dt>
+   <dd>multistage rocket</dd>
+   <dt>table</dt>
+   <dd>nest of tables</dd>
+  </dl>
+ </dd>
+</dl>
+
+
+ +
:last-of-type pseudo-class
+ +

Same as :nth-last-of-type(1). The :last-of-type pseudo-class represents an element that is the last sibling of its type in the list of children of its parent element.

+ +
+

Example:

+ +

The following selector represents the last data cell td of a table row.

+
+tr > td:last-of-type
+
+
+ +
:only-child pseudo-class
+ +

Represents an element that has a parent element and whose parent element has no other element children. Same as :first-child:last-child or :nth-child(1):nth-last-child(1), but with a lower specificity.

+ +
:only-of-type pseudo-class
+ +

Represents an element that has a parent element and whose parent element has no other element children with the same element name. Same as :first-of-type:last-of-type or :nth-of-type(1):nth-last-of-type(1), but with a lower specificity.

+ +
:empty pseudo-class
+ +

The :empty pseudo-class represents an element that has no children at all. In terms of the DOM, only element nodes and text nodes (including CDATA nodes and entity references) whose data has a non-zero length must be considered as affecting emptiness; comments, PIs, and other nodes must not affect whether an element is considered empty or not.

+ +
+

Examples:

+ +

p:empty is a valid representation of the following fragment:

+
+<p></p>
+
+ +

foo:empty is not a valid representation for the following fragments:

+
+<foo>bar</foo>
+
+
+<foo><bar>bla</bar></foo>
+
+
+<foo>this is not <bar>:empty</bar></foo>
+
+
+ +

6.6.6. Blank

+ +

This section intentionally left blank.

+ +

6.6.7. The negation pseudo-class

+ +

The negation pseudo-class, :not(X), is a functional notation taking a simple selector (excluding the negation pseudo-class itself and pseudo-elements) as an argument. It represents an element that is not represented by the argument.

+ +
+

Examples:

+ +

The following CSS selector matches all button elements in an HTML document that are not disabled.

+
+button:not([DISABLED])
+
+ +

The following selector represents all but FOO elements.

+
+*:not(FOO)
+
+ +

The following group of selectors represents all HTML elements except links.

+
+html|*:not(:link):not(:visited)
+
+
+ +

Default namespace declarations do not affect the argument of the negation pseudo-class unless the argument is a universal selector or a type selector.

+ +
+

Examples:

+ +

Assuming that the default namespace is bound to "http://example.com/", the following selector represents all elements that are not in that namespace:

+
+*|*:not(*)
+
+ +

The following CSS selector matches any element being hovered, regardless of its namespace. In particular, it is not limited to only matching elements in the default namespace that are not being hovered, and elements not in the default namespace don't match the rule when they are being hovered.

+
+*|*:not(:hover)
+
+
+ +

Note: the :not() pseudo allows useless selectors to be written. For instance :not(*|*), which represents no element at all, or foo:not(bar), which is equivalent to foo but with a higher specificity.

+ +

7. Pseudo-elements

+ +

Pseudo-elements create abstractions about the document tree beyond those specified by the document language. For instance, document languages do not offer mechanisms to access the first letter or first line of an element's content. Pseudo-elements allow designers to refer to this otherwise inaccessible information. Pseudo-elements may also provide designers a way to refer to content that does not exist in the source document (e.g., the ::before and ::after pseudo-elements give access to generated content).

+ +

A pseudo-element is made of two colons (::) followed by the name of the pseudo-element.

+ +

This :: notation is introduced by the current document in order to establish a discrimination between pseudo-classes and pseudo-elements. For compatibility with existing style sheets, user agents must also accept the previous one-colon notation for pseudo-elements introduced in CSS levels 1 and 2 (namely, :first-line, :first-letter, :before and :after). This compatibility is not allowed for the new pseudo-elements introduced in CSS level 3.

+ +

Only one pseudo-element may appear per selector, and if present it must appear after the sequence of simple selectors that represents the subjects of the selector. A future version of this specification may allow multiple pesudo-elements per selector.

+ +

7.1. The ::first-line pseudo-element

+ +

The ::first-line pseudo-element describes the contents of the first formatted line of an element.

+ +
+

CSS example:

+
+p::first-line { text-transform: uppercase }
+
+ +

The above rule means "change the letters of the first line of every paragraph to uppercase".

+
+ +

The selector p::first-line does not match any real HTML element. It does match a pseudo-element that conforming user agents will insert at the beginning of every paragraph.

+ +

Note that the length of the first line depends on a number of factors, including the width of the page, the font size, etc. Thus, an ordinary HTML paragraph such as:

+
+<P>This is a somewhat long HTML 
+paragraph that will be broken into several 
+lines. The first line will be identified
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

the lines of which happen to be broken as follows:

+
+THIS IS A SOMEWHAT LONG HTML PARAGRAPH THAT
+will be broken into several lines. The first
+line will be identified by a fictional tag 
+sequence. The other lines will be treated as 
+ordinary lines in the paragraph.
+
+ +

This paragraph might be "rewritten" by user agents to include the fictional tag sequence for ::first-line. This fictional tag sequence helps to show how properties are inherited.

+
+<P><P::first-line> This is a somewhat long HTML 
+paragraph that </P::first-line> will be broken into several
+lines. The first line will be identified 
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

If a pseudo-element breaks up a real element, the desired effect can often be described by a fictional tag sequence that closes and then re-opens the element. Thus, if we mark up the previous paragraph with a span element:

+
+<P><SPAN class="test"> This is a somewhat long HTML
+paragraph that will be broken into several
+lines.</SPAN> The first line will be identified
+by a fictional tag sequence. The other lines 
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

the user agent could simulate start and end tags for span when inserting the fictional tag sequence for ::first-line.

+
+<P><P::first-line><SPAN class="test"> This is a
+somewhat long HTML
+paragraph that will </SPAN></P::first-line><SPAN class="test"> be
+broken into several
+lines.</SPAN> The first line will be identified
+by a fictional tag sequence. The other lines
+will be treated as ordinary lines in the 
+paragraph.</P>
+
+ +

In CSS, the ::first-line pseudo-element can only be attached to a block-level element, an inline-block, a table-caption, or a table-cell.

+ +

The "first formatted line" of an element may occur inside a block-level descendant in the same flow (i.e., a block-level descendant that is not positioned and not a float). E.g., the first line of the div in <DIV><P>This line...</P></DIV> is the first line of the p (assuming that both p and div are block-level).

+ +

The first line of a table-cell or inline-block cannot be the first formatted line of an ancestor element. Thus, in <DIV><P STYLE="display: inline-block">Hello<BR>Goodbye</P> etcetera</DIV> the first formatted line of the div is not the line "Hello".

+ +

Note that the first line of the p in this fragment: <p><br>First... doesn't contain any letters (assuming the default style for br in HTML 4). The word "First" is not on the first formatted line.

+ +

A UA should act as if the fictional start tags of the ::first-line pseudo-elements were nested just inside the innermost enclosing block-level element. (Since CSS1 and CSS2 were silent on this case, authors should not rely on this behavior.) Here is an example. The fictional tag sequence for

+
+<DIV>
+  <P>First paragraph</P>
+  <P>Second paragraph</P>
+</DIV>
+
+ +

is

+
+<DIV>
+  <P><DIV::first-line><P::first-line>First paragraph</P::first-line></DIV::first-line></P>
+  <P><P::first-line>Second paragraph</P::first-line></P>
+</DIV>
+
+ +

The ::first-line pseudo-element is similar to an inline-level element, but with certain restrictions. In CSS, the following properties apply to a ::first-line pseudo-element: font properties, color property, background properties, 'word-spacing', 'letter-spacing', 'text-decoration', 'vertical-align', 'text-transform', 'line-height'. UAs may apply other properties as well.

+ +

7.2. The ::first-letter pseudo-element

+ +

The ::first-letter pseudo-element represents the first letter of the first line of a block, if it is not preceded by any other content (such as images or inline tables) on its line. The ::first-letter pseudo-element may be used for "initial caps" and "drop caps", which are common typographical effects. This type of initial letter is similar to an inline-level element if its 'float' property is 'none'; otherwise, it is similar to a floated element.

+ +

In CSS, these are the properties that apply to ::first-letter pseudo-elements: font properties, 'text-decoration', 'text-transform', 'letter-spacing', 'word-spacing' (when appropriate), 'line-height', 'float', 'vertical-align' (only if 'float' is 'none'), margin properties, padding properties, border properties, color property, background properties. UAs may apply other properties as well. To allow UAs to render a typographically correct drop cap or initial cap, the UA may choose a line-height, width and height based on the shape of the letter, unlike for normal elements.

+ +
+

Example:

+ +

This example shows a possible rendering of an initial cap. Note that the 'line-height' that is inherited by the ::first-letter pseudo-element is 1.1, but the UA in this example has computed the height of the first letter differently, so that it doesn't cause any unnecessary space between the first two lines. Also note that the fictional start tag of the first letter is inside the span, and thus the font weight of the first letter is normal, not bold as the span:

+
+p { line-height: 1.1 }
+p::first-letter { font-size: 3em; font-weight: normal }
+span { font-weight: bold }
+...
+<p><span>Het hemelsche</span> gerecht heeft zich ten lange lesten<br>
+Erbarremt over my en mijn benaeuwde vesten<br>
+En arme burgery, en op mijn volcx gebed<br>
+En dagelix geschrey de bange stad ontzet.
+
+ +
+

Image illustrating the ::first-letter pseudo-element

+
+
+ +
+

The following CSS will make a drop cap initial letter span about two lines:

+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<HTML>
+ <HEAD>
+  <TITLE>Drop cap initial letter</TITLE>
+  <STYLE type="text/css">
+   P               { font-size: 12pt; line-height: 1.2 }
+   P::first-letter { font-size: 200%; font-weight: bold; float: left }
+   SPAN            { text-transform: uppercase }
+  </STYLE>
+ </HEAD>
+ <BODY>
+  <P><SPAN>The first</SPAN> few words of an article
+    in The Economist.</P>
+ </BODY>
+</HTML>
+
+ +

This example might be formatted as follows:

+ +
+

Image illustrating the combined effect of the ::first-letter and ::first-line pseudo-elements

+
+ +

The fictional tag sequence is:

+
+<P>
+<SPAN>
+<P::first-letter>
+T
+</P::first-letter>he first
+</SPAN> 
+few words of an article in the Economist.
+</P>
+
+ +

Note that the ::first-letter pseudo-element tags abut the content (i.e., the initial character), while the ::first-line pseudo-element start tag is inserted right after the start tag of the block element.

+
+ +

In order to achieve traditional drop caps formatting, user agents may approximate font sizes, for example to align baselines. Also, the glyph outline may be taken into account when formatting.

+ +

Punctuation (i.e, characters defined in Unicode in the "open" (Ps), "close" (Pe), "initial" (Pi). "final" (Pf) and "other" (Po) punctuation classes), that precedes or follows the first letter should be included. [UNICODE]

+ +
+

Quotes that precede the first letter should be included.

+
+ +

The ::first-letter also applies if the first letter is in fact a digit, e.g., the "6" in "67 million dollars is a lot of money."

+ +

In CSS, the ::first-letter pseudo-element applies to block, list-item, table-cell, table-caption, and inline-block elements. A future version of this specification may allow this pesudo-element to apply to more element types.

+ +

The ::first-letter pseudo-element can be used with all such elements that contain text, or that have a descendant in the same flow that contains text. A UA should act as if the fictional start tag of the ::first-letter pseudo-element is just before the first text of the element, even if that first text is in a descendant.

+ +
+

Example:

+ +

The fictional tag sequence for this HTMLfragment:

+
+<div>
+<p>The first text.
+
+ +

is:

+
+<div>
+<p><div::first-letter><p::first-letter>T</...></...>he first text.
+
+
+ +

The first letter of a table-cell or inline-block cannot be the first letter of an ancestor element. Thus, in <DIV><P STYLE="display: inline-block">Hello<BR>Goodbye</P> etcetera</DIV> the first letter of the div is not the letter "H". In fact, the div doesn't have a first letter.

+ +

The first letter must occur on the first formatted line. For example, in this fragment: <p><br>First... the first line doesn't contain any letters and ::first-letter doesn't match anything (assuming the default style for br in HTML 4). In particular, it does not match the "F" of "First."

+ +

In CSS, if an element is a list item ('display: list-item'), the ::first-letter applies to the first letter in the principal box after the marker. UAs may ignore ::first-letter on list items with 'list-style-position: inside'. If an element has ::before or ::after content, the ::first-letter applies to the first letter of the element including that content.

+ +
+

Example:

+ +

After the rule 'p::before {content: "Note: "}', the selector 'p::first-letter' matches the "N" of "Note".

+
+ +

Some languages may have specific rules about how to treat certain letter combinations. In Dutch, for example, if the letter combination "ij" appears at the beginning of a word, both letters should be considered within the ::first-letter pseudo-element.

+ +

If the letters that would form the ::first-letter are not in the same element, such as "'T" in <p>'<em>T..., the UA may create a ::first-letter pseudo-element from one of the elements, both elements, or simply not create a pseudo-element.

+ +

Similarly, if the first letter(s) of the block are not at the start of the line (for example due to bidirectional reordering), then the UA need not create the pseudo-element(s).

+ +
+

Example:

+ +

The following example illustrates how overlapping pseudo-elements may interact. The first letter of each P element will be green with a font size of '24pt'. The rest of the first formatted line will be 'blue' while the rest of the paragraph will be 'red'.

+
+p { color: red; font-size: 12pt }
+p::first-letter { color: green; font-size: 200% }
+p::first-line { color: blue }
+
+<P>Some text that ends up on two lines</P>
+
+ +

Assuming that a line break will occur before the word "ends", the fictional tag sequence for this fragment might be:

+
+<P>
+<P::first-line>
+<P::first-letter> 
+S 
+</P::first-letter>ome text that 
+</P::first-line> 
+ends up on two lines 
+</P>
+
+ +

Note that the ::first-letter element is inside the ::first-line element. Properties set on ::first-line are inherited by ::first-letter, but are overridden if the same property is set on ::first-letter.

+
+ +

7.3. The ::selection pseudo-element

+ +

The ::selection pseudo-element applies to the portion of a document that has been highlighted by the user. This also applies, for example, to selected text within an editable text field. This pseudo-element should not be confused with the :checked pseudo-class (which used to be named :selected)

+ +

Although the ::selection pseudo-element is dynamic in nature, and is altered by user action, it is reasonable to expect that when a UA re-renders to a static medium (such as a printed page, see [CSS21]) which was originally rendered to a dynamic medium (like screen), the UA may wish to transfer the current ::selection state to that other medium, and have all the appropriate formatting and rendering take effect as well. This is not required — UAs may omit the ::selection pseudo-element for static media.

+ +

These are the CSS properties that apply to ::selection pseudo-elements: color, background, cursor (optional), outline (optional). The computed value of the 'background-image' property on ::selection may be ignored.

+ +

7.4. The ::before and ::after pseudo-elements

+ +

The ::before and ::after pseudo-elements can be used to describe generated content before or after an element's content. They are explained in CSS 2.1 [CSS21].

+ +

When the ::first-letter and ::first-line pseudo-elements are combined with ::before and ::after, they apply to the first letter or line of the element including the inserted text.

+ +

8. Combinators

+ +

8.1. Descendant combinator

+ +

At times, authors may want selectors to describe an element that is the descendant of another element in the document tree (e.g., "an EM element that is contained within an H1 element"). Descendant combinators express such a relationship. A descendant combinator is white space that separates two sequences of simple selectors. A selector of the form "A B" represents an element B that is an arbitrary descendant of some ancestor element A.

+ +
+

Examples:

+ +

For example, consider the following selector:

+
+h1 em
+
+ +

It represents an em element being the descendant of an h1 element. It is a correct and valid, but partial, description of the following fragment:

+
+<h1>This <span class="myclass">headline
+is <em>very</em> important</span></h1>
+
+ +

The following selector:

+
+div * p
+
+ +

represents a p element that is a grandchild or later descendant of a div element. Note the whitespace on either side of the "*" is not part of the universal selector; the whitespace is a combinator indicating that the DIV must be the ancestor of some element, and that that element must be an ancestor of the P.

+ +

The following selector, which combines descendant combinators and attribute selectors, represents an element that (1) has the href attribute set and (2) is inside a p that is itself inside a div:

+
+div p *[href]
+
+
+ +

8.2. Child combinators

+ +

A child combinator describes a childhood relationship between two elements. A child combinator is made of the "greater-than sign" (>) character and separates two sequences of simple selectors.

+ +
+

Examples:

+ +

The following selector represents a p element that is child of body:

+
+body > p
+
+ +

The following example combines descendant combinators and child combinators.

+
+div ol>li p
+
+ +

It represents a p element that is a descendant of an li element; the li element must be the child of an ol element; the ol element must be a descendant of a div. Notice that the optional white space around the ">" combinator has been left out.

+
+ +

For information on selecting the first child of an element, please see the section on the :first-child pseudo-class above.

+ +

8.3. Sibling combinators

+ +

There are two different sibling combinators: the adjacent sibling combinator and the general sibling combinator. In both cases, non-element nodes (e.g. text between elements) are ignored when considering adjacency of elements.

+ +

8.3.1. Adjacent sibling combinator

+ +

The adjacent sibling combinator is made of the "plus sign" (U+002B, +) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence immediately precedes the element represented by the second one.

+ +
+

Examples:

+ +

The following selector represents a p element immediately following a math element:

+
+math + p
+
+ +

The following selector is conceptually similar to the one in the previous example, except that it adds an attribute selector — it adds a constraint to the h1 element, that it must have class="opener":

+
+h1.opener + h2
+
+
+ +

8.3.2. General sibling combinator

+ +

The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.

+ +
+

Example:

+
+h1 ~ pre
+
+ +

represents a pre element following an h1. It is a correct and valid, but partial, description of:

+
+<h1>Definition of the function a</h1>
+<p>Function a(x) has to be applied to all figures in the table.</p>
+<pre>function a(x) = 12x/13.5</pre>
+
+
+ +

9. Calculating a selector's specificity

+ +

A selector's specificity is calculated as follows:

+ + + +

Selectors inside the negation pseudo-class are counted like any other, but the negation itself does not count as a pseudo-class.

+ +

Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity.

+ +
+

Examples:

+
+*               /* a=0 b=0 c=0 -> specificity =   0 */
+LI              /* a=0 b=0 c=1 -> specificity =   1 */
+UL LI           /* a=0 b=0 c=2 -> specificity =   2 */
+UL OL+LI        /* a=0 b=0 c=3 -> specificity =   3 */
+H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity =  11 */
+UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */
+LI.red.level    /* a=0 b=2 c=1 -> specificity =  21 */
+#x34y           /* a=1 b=0 c=0 -> specificity = 100 */
+#s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 101 */
+
+
+ +

Note: the specificity of the styles specified in an HTML style attribute is described in CSS 2.1. [CSS21].

+ +

10. The grammar of Selectors

+ +

10.1. Grammar

+ +

The grammar below defines the syntax of Selectors. It is globally LL(1) and can be locally LL(2) (but note that most UA's should not use it directly, since it doesn't express the parsing conventions). The format of the productions is optimized for human consumption and some shorthand notations beyond Yacc (see [YACC]) are used:

+ + + +

The productions are:

+
+selectors_group
+  : selector [ COMMA S* selector ]*
+  ;
+
+selector
+  : simple_selector_sequence [ combinator simple_selector_sequence ]*
+  ;
+
+combinator
+  /* combinators can be surrounded by white space */
+  : PLUS S* | GREATER S* | TILDE S* | S+
+  ;
+
+simple_selector_sequence
+  : [ type_selector | universal ]
+    [ HASH | class | attrib | pseudo | negation ]*
+  | [ HASH | class | attrib | pseudo | negation ]+
+  ;
+
+type_selector
+  : [ namespace_prefix ]? element_name
+  ;
+
+namespace_prefix
+  : [ IDENT | '*' ]? '|'
+  ;
+
+element_name
+  : IDENT
+  ;
+
+universal
+  : [ namespace_prefix ]? '*'
+  ;
+
+class
+  : '.' IDENT
+  ;
+
+attrib
+  : '[' S* [ namespace_prefix ]? IDENT S*
+        [ [ PREFIXMATCH |
+            SUFFIXMATCH |
+            SUBSTRINGMATCH |
+            '=' |
+            INCLUDES |
+            DASHMATCH ] S* [ IDENT | STRING ] S*
+        ]? ']'
+  ;
+
+pseudo
+  /* '::' starts a pseudo-element, ':' a pseudo-class */
+  /* Exceptions: :first-line, :first-letter, :before and :after. */
+  /* Note that pseudo-elements are restricted to one per selector and */
+  /* occur only in the last simple_selector_sequence. */
+  : ':' ':'? [ IDENT | functional_pseudo ]
+  ;
+
+functional_pseudo
+  : FUNCTION S* expression ')'
+  ;
+
+expression
+  /* In CSS3, the expressions are identifiers, strings, */
+  /* or of the form "an+b" */
+  : [ [ PLUS | '-' | DIMENSION | NUMBER | STRING | IDENT ] S* ]+
+  ;
+
+negation
+  : NOT S* negation_arg S* ')'
+  ;
+
+negation_arg
+  : type_selector | universal | HASH | class | attrib | pseudo
+  ;
+
+ +

10.2. Lexical scanner

+ +

The following is the tokenizer, written in Flex (see [FLEX]) notation. The tokenizer is case-insensitive.

+ +

The two occurrences of "\377" represent the highest character number that current versions of Flex can deal with (decimal 255). They should be read as "\4177777" (decimal 1114111), which is the highest possible code point in Unicode/ISO-10646. [UNICODE]

+
+%option case-insensitive
+
+ident     [-]?{nmstart}{nmchar}*
+name      {nmchar}+
+nmstart   [_a-z]|{nonascii}|{escape}
+nonascii  [^\0-\177]
+unicode   \\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?
+escape    {unicode}|\\[^\n\r\f0-9a-f]
+nmchar    [_a-z0-9-]|{nonascii}|{escape}
+num       [0-9]+|[0-9]*\.[0-9]+
+string    {string1}|{string2}
+string1   \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*\"
+string2   \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*\'
+invalid   {invalid1}|{invalid2}
+invalid1  \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*
+invalid2  \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*
+nl        \n|\r\n|\r|\f
+w         [ \t\r\n\f]*
+
+%%
+
+[ \t\r\n\f]+     return S;
+
+"~="             return INCLUDES;
+"|="             return DASHMATCH;
+"^="             return PREFIXMATCH;
+"$="             return SUFFIXMATCH;
+"*="             return SUBSTRINGMATCH;
+{ident}          return IDENT;
+{string}         return STRING;
+{ident}"("       return FUNCTION;
+{num}            return NUMBER;
+"#"{name}        return HASH;
+{w}"+"           return PLUS;
+{w}">"           return GREATER;
+{w}","           return COMMA;
+{w}"~"           return TILDE;
+":not("          return NOT;
+@{ident}         return ATKEYWORD;
+{invalid}        return INVALID;
+{num}%           return PERCENTAGE;
+{num}{ident}     return DIMENSION;
+"<!--"           return CDO;
+"-->"            return CDC;
+
+"url("{w}{string}{w}")"                           return URI;
+"url("{w}([!#$%&*-~]|{nonascii}|{escape})*{w}")"  return URI;
+U\+[0-9a-f?]{1,6}(-[0-9a-f]{1,6})?                return UNICODE_RANGE;
+
+\/\*[^*]*\*+([^/*][^*]*\*+)*\/                    /* ignore comments */
+
+.                return *yytext;
+
+ +

11. Namespaces and down-level clients

+ +

An important issue is the interaction of CSS selectors with XML documents in web clients that were produced prior to this document. Unfortunately, due to the fact that namespaces must be matched based on the URI which identifies the namespace, not the namespace prefix, some mechanism is required to identify namespaces in CSS by their URI as well. Without such a mechanism, it is impossible to construct a CSS style sheet which will properly match selectors in all cases against a random set of XML documents. However, given complete knowledge of the XML document to which a style sheet is to be applied, and a limited use of namespaces within the XML document, it is possible to construct a style sheet in which selectors would match elements and attributes correctly.

+ +

It should be noted that a down-level CSS client will (if it properly conforms to CSS forward compatible parsing rules) ignore all @namespace at-rules, as well as all style rules that make use of namespace qualified element type or attribute selectors. The syntax of delimiting namespace prefixes in CSS was deliberately chosen so that down-level CSS clients would ignore the style rules rather than possibly match them incorrectly.

+ +

The use of default namespaces in CSS makes it possible to write element type selectors that will function in both namespace aware CSS clients as well as down-level clients. It should be noted that down-level clients may incorrectly match selectors against XML elements in other namespaces.

+ +

The following are scenarios and examples in which it is possible to construct style sheets which would function properly in web clients that do not implement this proposal.

+ +
    +
  1. +

    The XML document does not use namespaces.

    + +
      +
    • In this case, it is obviously not necessary to declare or use namespaces in the style sheet. Standard CSS element type and attribute selectors will function adequately in a down-level client.
    • + +
    • In a CSS namespace aware client, the default behavior of element selectors matching without regard to namespace will function properly against all elements, since no namespaces are present. However, the use of specific element type selectors that match only elements that have no namespace ("|name") will guarantee that selectors will match only XML elements that do not have a declared namespace.
    • +
    +
  2. + +
  3. +

    The XML document defines a single, default namespace used throughout the document. No namespace prefixes are used in element names.

    + +
      +
    • In this case, a down-level client will function as if namespaces were not used in the XML document at all. Standard CSS element type and attribute selectors will match against all elements.
    • +
    +
  4. + +
  5. +

    The XML document does not use a default namespace, all namespace prefixes used are known to the style sheet author, and there is a direct mapping between namespace prefixes and namespace URIs. (A given prefix may only be mapped to one namespace URI throughout the XML document; there may be multiple prefixes mapped to the same URI).

    + +
      +
    • In this case, the down-level client will view and match element type and attribute selectors based on their fully qualified name, not the local part as outlined in the Type selectors and Namespaces section. CSS selectors may be declared using an escaped colon "\:" to describe the fully qualified names, e.g. "html\:h1" will match <html:h1>. Selectors using the qualified name will only match XML elements that use the same prefix. Other namespace prefixes used in the XML that are mapped to the same URI will not match as expected unless additional CSS style rules are declared for them.
    • + +
    • Note that selectors declared in this fashion will only match in down-level clients. A CSS namespace aware client will match element type and attribute selectors based on the name's local part. Selectors declared with the fully qualified name will not match (unless there is no namespace prefix in the fully qualified name).
    • +
    +
  6. +
+ +

In other scenarios: when the namespace prefixes used in the XML are not known in advance by the style sheet author; or a combination of elements with no namespace are used in conjunction with elements using a default namespace; or the same namespace prefix is mapped to different namespace URIs within the same document, or in different documents; it is impossible to construct a CSS style sheet that will function properly against all elements in those documents, unless, the style sheet is written using a namespace URI syntax (as outlined in this document or similar) and the document is processed by a CSS and XML namespace aware client.

+ +

12. Profiles

+ +

Each specification using Selectors must define the subset of W3C Selectors it allows and excludes, and describe the local meaning of all the components of that subset.

+ +

Non normative examples:

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Selectors profile
SpecificationCSS level 1
Acceptstype selectors
+ class selectors
+ ID selectors
+ :link, :visited and :active pseudo-classes
+ descendant combinator
+ ::first-line and ::first-letter pseudo-elements
Excludes +

universal selector
+ attribute selectors
+ :hover and :focus pseudo-classes
+ :target pseudo-class
+ :lang() pseudo-class
+ all UI element states pseudo-classes
+ all structural pseudo-classes
+ negation pseudo-class
+ all UI element fragments pseudo-elements
+ ::before and ::after pseudo-elements
+ child combinators
+ sibling combinators

+ +

namespaces

+
Extra constraintsonly one class selector allowed per sequence of simple selectors

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Selectors profile
SpecificationCSS level 2
Acceptstype selectors
+ universal selector
+ attribute presence and values selectors
+ class selectors
+ ID selectors
+ :link, :visited, :active, :hover, :focus, :lang() and :first-child pseudo-classes
+ descendant combinator
+ child combinator
+ adjacent sibling combinator
+ ::first-line and ::first-letter pseudo-elements
+ ::before and ::after pseudo-elements
Excludes +

content selectors
+ substring matching attribute selectors
+ :target pseudo-classes
+ all UI element states pseudo-classes
+ all structural pseudo-classes other than :first-child
+ negation pseudo-class
+ all UI element fragments pseudo-elements
+ general sibling combinators

+ +

namespaces

+
Extra constraintsmore than one class selector per sequence of simple selectors (CSS1 constraint) allowed
+ +

In CSS, selectors express pattern matching rules that determine which style rules apply to elements in the document tree.

+ +

The following selector (CSS level 2) will match all anchors a with attribute name set inside a section 1 header h1:

+
+h1 a[name]
+
+ +

All CSS declarations attached to such a selector are applied to elements matching it.

+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Selectors profile
SpecificationSTTS 3
Accepts +

type selectors
+ universal selectors
+ attribute selectors
+ class selectors
+ ID selectors
+ all structural pseudo-classes
+ all combinators

+ +

namespaces

+
Excludesnon-accepted pseudo-classes
+ pseudo-elements
Extra constraintssome selectors and combinators are not allowed in fragment descriptions on the right side of STTS declarations.
+ +

Selectors can be used in STTS 3 in two different manners:

+ +
    +
  1. a selection mechanism equivalent to CSS selection mechanism: declarations attached to a given selector are applied to elements matching that selector,
  2. + +
  3. fragment descriptions that appear on the right side of declarations.
  4. +
+
+ +

13. Conformance and requirements

+ +

This section defines conformance with the present specification only.

+ +

The inability of a user agent to implement part of this specification due to the limitations of a particular device (e.g., non interactive user agents will probably not implement dynamic pseudo-classes because they make no sense without interactivity) does not imply non-conformance.

+ +

All specifications reusing Selectors must contain a Profile listing the subset of Selectors it accepts or excludes, and describing the constraints it adds to the current specification.

+ +

Invalidity is caused by a parsing error, e.g. an unrecognized token or a token which is not allowed at the current parsing point.

+ +

User agents must observe the rules for handling parsing errors:

+ + + +

Specifications reusing Selectors must define how to handle parsing errors. (In the case of CSS, the entire rule in which the selector is used is dropped.)

+ +

14. Tests

+ +

This specification has a test suite allowing user agents to verify their basic conformance to the specification. This test suite does not pretend to be exhaustive and does not cover all possible combined cases of Selectors.

+ +

15. Acknowledgements

+ +

The CSS working group would like to thank everyone who has sent comments on this specification over the years.

+ +

The working group would like to extend special thanks to Donna McManus, Justin Baker, Joel Sklar, and Molly Ives Brower who perfermed the final editorial review.

+ +

16. References

+ +
+
[CSS1]
+ +
Bert Bos, Håkon Wium Lie; "Cascading Style Sheets, level 1", W3C Recommendation, 17 Dec 1996, revised 11 Jan 1999
+ +
(http://www.w3.org/TR/REC-CSS1)
+ +
[CSS21]
+ +
Bert Bos, Tantek Çelik, Ian Hickson, Håkon Wium Lie, editors; "Cascading Style Sheets, level 2 revision 1", W3C Working Draft, 13 June 2005
+ +
(http://www.w3.org/TR/CSS21)
+ +
[CWWW]
+ +
Martin J. Dürst, François Yergeau, Misha Wolf, Asmus Freytag, Tex Texin, editors; "Character Model for the World Wide Web", W3C Recommendation, 15 February 2005
+ +
(http://www.w3.org/TR/charmod/)
+ +
[FLEX]
+ +
"Flex: The Lexical Scanner Generator", Version 2.3.7, ISBN 1882114213
+ +
[HTML4]
+ +
Dave Ragget, Arnaud Le Hors, Ian Jacobs, editors; "HTML 4.01 Specification", W3C Recommendation, 24 December 1999
+ +
(http://www.w3.org/TR/html4/)
+ +
[MATH]
+ +
Patrick Ion, Robert Miner, editors; "Mathematical Markup Language (MathML) 1.01", W3C Recommendation, revision of 7 July 1999
+ +
(http://www.w3.org/TR/REC-MathML/)
+ +
[RFC3066]
+ +
H. Alvestrand; "Tags for the Identification of Languages", Request for Comments 3066, January 2001
+ +
(http://www.ietf.org/rfc/rfc3066.txt)
+ +
[STTS]
+ +
Daniel Glazman; "Simple Tree Transformation Sheets 3", Electricité de France, submission to the W3C, 11 November 1998
+ +
(http://www.w3.org/TR/NOTE-STTS3)
+ +
[SVG]
+ +
Jon Ferraiolo, 藤沢 淳, Dean Jackson, editors; "Scalable Vector Graphics (SVG) 1.1 Specification", W3C Recommendation, 14 January 2003
+ +
(http://www.w3.org/TR/SVG/)
+ +
[UNICODE]
+ +
The Unicode Standard, Version 4.1, The Unicode Consortium. Boston, MA, Addison-Wesley, March 2005. ISBN 0-321-18578-1, as amended by Unicode 4.0.1 and Unicode 4.1.0.
+ +
(http://www.unicode.org/versions/)
+ +
[XML10]
+ +
Tim Bray, Jean Paoli, C. M. Sperberg-McQueen, Eve Maler, François Yergeau, editors; "Extensible Markup Language (XML) 1.0 (Third Edition)", W3C Recommendation, 4 February 2004
+ +
(http://www.w3.org/TR/REC-xml/)
+ +
[XMLNAMES]
+ +
Tim Bray, Dave Hollander, Andrew Layman, editors; "Namespaces in XML", W3C Recommendation, 14 January 1999
+ +
(http://www.w3.org/TR/REC-xml-names/)
+ +
[YACC]
+ +
S. C. Johnson; "YACC — Yet another compiler compiler", Technical Report, Murray Hill, 1975
+
+ +
+ test +
+ +
+
+ test + +
+ test +
+ +
+
+ test +
+
+
+
+ +
+ d1d1 d2d2 d3d3 d4d4 d5d5 d6d6 +
+ +
+ d1 d1 d2 d2 d3 d3 d4 d4 d5 d5 d6 d6 +
+ + diff --git a/test_new/browser/fixtures/speed/selectors.html b/test_new/browser/fixtures/speed/selectors.html new file mode 100644 index 0000000..f9e0e41 --- /dev/null +++ b/test_new/browser/fixtures/speed/selectors.html @@ -0,0 +1,5055 @@ + + + + Selectors Level 4 + + + + + + + + + + + + + + + + +

Jump to Table of Contents Collapse Sidebar

+
+

+

Selectors Level 4

+

W3C Working Draft,

+
+
+
This version: +
https://www.w3.org/TR/2018/WD-selectors-4-20180202/ +
Latest published version: +
https://www.w3.org/TR/selectors-4/ +
Editor's Draft: +
https://drafts.csswg.org/selectors +
Previous Versions: +
+
+
+
+
Test Suite: +
http://test.csswg.org/suites/selectors-4_dev/nightly-unstable/ +
Issue Tracking: +
Inline In Spec +
GitHub Issues +
Editors: +
Elika J. Etemad / fantasai (Invited Expert) +
Tab Atkins Jr. (Google) +
Former Editors: +
Tantek Çelik +
Daniel Glazman +
Ian Hickson +
Peter Linss +
John Williams +
+
+
+ +
+
+
+

Abstract

+

Selectors + are patterns that match against elements in a tree, and as such form +one of several technologies that can be used to select nodes in a +document. Selectors have been optimized for use with HTML and XML, and +are designed to be usable in performance-critical code. They are a core +component of CSS (Cascading Style Sheets), which uses Selectors to bind style properties to elements in the docu ment. + +Selectors Level 4 describes the selectors that already exist in [SELECT], and further introduces new selectors for CSS and other languages that may need them.

+ CSS is a language for describing the rendering of structured documents +(such as HTML and XML) +on screen, on paper, in speech, etc. +
+

Status of this document

+
+

This section describes the status of this document at the time of + its publication. Other documents may supersede this document. A list of + current W3C publications and the latest revision of this technical report + can be found in the W3C technical reports + index at https://www.w3.org/TR/.

+

Publication as a Working Draft does not imply endorsement by the W3C + Membership. This is a draft document and may be updated, replaced or + obsoleted by other documents at any time. It is inappropriate to cite this + document as other than work in progress.

+

GitHub Issues are preferred for discussion of this specification. + When filing an issue, please put the text “selectors” in the title, + preferably like this: + “[selectors] …summary of comment…”. + All issues and comments are archived, + and there is also a historical archive.

+

This document was produced by the CSS Working Group (part of + the Style Activity).

+

This document was produced by a group operating under the W3C Patent Policy. + W3C maintains a public list of any patent disclosures made in + connection with the deliverables of the group; that page also includes + instructions for disclosing a patent. An individual who has actual + knowledge of a patent which the individual believes contains Essential + Claim(s) must disclose the information in accordance with section + 6 of the W3C Patent Policy.

+

This document is governed by the 1 March 2017 W3C Process Document.

+

+
+
+

The following features are at-risk, and may be dropped during the CR period:

+ +

“At-risk” is a W3C Process term-of-art, and does not necessarily +imply that the feature is in danger of being dropped or delayed. It +means that the WG believes the feature may have difficulty being +interoperably implemented in a timely manner, and marking it as such +allows the WG to drop the feature if necessary when transitioning to the + Proposed Rec stage, without having to publish a new Candidate Rec +without the feature first.

+
+ +
+

1. Introduction

+

This section is not normative.

+

A selector is a boolean predicate + that takes an element in a tree structure + and tests whether the element matches the selector or not.

+

These expressions may be used for many things:

+
    +
  • directly on an element to test whether it matches some criteria, + such as in the element.matches() function defined in [DOM] +
  • applied to an entire tree of elements + to filter it into a set of elements that match the criteria, + such as in the document.queryAll() function defined in [DOM] or the selector of a CSS style rule. +
  • used "in reverse" to generate markup that would match a given selector, + such as in HAML or Emmet. +
+

Selectors Levels 1, 2, and 3 are defined as the subsets of selector + functionality defined in the CSS1, CSS2.1, and Selectors Level 3 specifications, respectively. This module defines Selectors Level 4.

+

1.1. Module Interactions

+

This module replaces the definitions of + and extends the set of selectors defined for CSS in [SELECT] and [CSS21].

+

Pseudo-element selectors, + which define abstract elements in a rendering tree, + are not part of this specification: + their generic syntax is described here, + but, due to their close integration with the rendering model and irrelevance to other uses such as DOM queries, + they will be defined in other modules.

+

2. Selectors Overview

+

This section is non-normative, as it merely summarizes the + following sections.

+

A selector represents a structure. This structure can be used as a + condition (e.g. in a CSS rule) that determines which elements a + selector matches in the document tree, or as a flat description of the + HTML or XML fragment corresponding to that structure.

+

Selectors may range from simple element names to rich contextual + representations.

+

The following table summarizes the Selector syntax:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Pattern + Represents + Section + Level +
* + any element + §5.2 Universal selector + 2 +
E + an element of type E + §5.1 Type (tag name) selector + 1 +
E:not(s1, s2) + an E element that does not match either compound selector s1 or compound selector s2 + §4.3 The Negation Pseudo-class: :not() + 3/4 +
E:matches(s1, s2) + an E element that matches compound selector s1 and/or compound selector s2 + §4.2 The Matches-any Pseudo-class: :matches() + 4 +
E:something(s1, s2) + an E element that matches compound selector s1 and/or compound selector s2 but contributes no specificity. + §4.4 The Specificity-adjustment Pseudo-class: :something() + 4 +
E:has(rs1, rs2) + an E element, + if either of the relative selectors rs1 or rs2, + when evaluated with E as the :scope elements, + match an element + §4.5 The Relational Pseudo-class: :has() + 4 +
E.warning + an E element belonging to the class warning (the document language specifies how class is determined). + §6.6 Class selectors + 1 +
E#myid + an E element with ID equal to myid. + §6.7 ID selectors + 1 +
E[foo] + an E element with a foo attribute + §6 Attribute selectors + 2 +
E[foo="bar"] + an E element whose foo attribute value is + exactly equal to bar + §6 Attribute selectors + 2 +
E[foo="bar" i] + an E element whose foo attribute value is + exactly equal to any (ASCII-range) case-permutation of bar + §6.3 Case-sensitivity + 4 +
E[foo~="bar"] + an E element whose foo attribute value is + a list of whitespace-separated values, one of which is + exactly equal to bar + §6 Attribute selectors + 2 +
E[foo^="bar"] + an E element whose foo attribute value + begins exactly with the string bar + §6.2 Substring matching attribute selectors + 3 +
E[foo$="bar"] + an E element whose foo attribute value + ends exactly with the string bar + §6.2 Substring matching attribute selectors + 3 +
E[foo*="bar"] + an E element whose foo attribute value + contains the substring bar + §6.2 Substring matching attribute selectors + 3 +
E[foo|="en"] + an E element whose foo attribute value is + a hyphen-separated list of values beginning with en + §6 Attribute selectors + 2 +
E:dir(ltr) + an element of type E in with left-to-right directionality + (the document language specifies how directionality is determined) + §7.1 The Directionality Pseudo-class: :dir() + 4 +
E:lang(zh, "*-hant") + an element of type E tagged as being either in Chinese + (any dialect or writing system) + or otherwise written with traditional Chinese characters + §7.2 The Language Pseudo-class: :lang() + 2/4 +
E:any-link + an E element being the source anchor of a hyperlink + §8.1 The Hyperlink Pseudo-class: :any-link + 4 +
E:link + an E element being the source anchor of a hyperlink + of which the target is not yet visited + §8.2 The Link History Pseudo-classes: :link and :visited + 1 +
E:visited + an E element being the source anchor of a hyperlink + of which the target is already visited + §8.2 The Link History Pseudo-classes: :link and :visited + 1 +
E:local-link + an E element being the source anchor of a hyperlink + targetting the current URL + §8.3 The Local Link Pseudo-class: :local-link + 4 +
E:target + an E element being the target of the current URL + §8.4 The Target Pseudo-class: :target + 3 +
E:target-within + an E element that is the target of the current URL or contains an element that does. + §8.5 The Target Container Pseudo-class: :target-within + 4 +
E:scope + an E element being a designated reference element + §8.6 The Reference Element Pseudo-class: :scope + 4 +
E:current + an E element that is currently presented in a time-dimensional canvas + §10 Time-dimensional Pseudo-classes + 4 +
E:current(s) + an E element that is the deepest :current element that + matches selector s + §10 Time-dimensional Pseudo-classes + 4 +
E:past + an E element that is in the past in a time-dimensional canvas + §10 Time-dimensional Pseudo-classes + 4 +
E:future + an E element that is in the future in a time-dimensional canvas + §10 Time-dimensional Pseudo-classes + 4 +
E:active + an E element that is in an activated state + §9 User Action Pseudo-classes + 1 +
E:hover + an E element that is under the cursor, + or that has a descendant under the cursor + §9 User Action Pseudo-classes + 2 +
E:focus + an E element that has user input focus + §9 User Action Pseudo-classes + 2 +
E:focus-within + an E element that has user input focus or contains an element that has input focus. + §9.5 The Focus Container Pseudo-class: :focus-within + 4 +
E:focus-visible + an E element that has user input focus, + and the UA has determined that a focus ring or other indicator + should be drawn for that element + §9 User Action Pseudo-classes + 4 +
E:drop + an E element that can possibly receive a drop + §9.6 The Drop Target Pseudo-class: :drop and :drop() + 4 +
E:drop(active) + an E element that is the current drop target for the item being dragged + §9.6 The Drop Target Pseudo-class: :drop and :drop() + 4 +
E:drop(valid) + an E element that could receive the item currently being dragged + §9.6 The Drop Target Pseudo-class: :drop and :drop() + 4 +
E:drop(invalid) + an E element that cannot receive the item currently being dragged, but could receive some other item + §9.6 The Drop Target Pseudo-class: :drop and :drop() + 4 +
E:enabled
E:disabled
+
a user interface element E that is enabled or disabled, respectively + §12.1.1 The :enabled and :disabled Pseudo-classes + 3 +
E:read-write
E:read-only +
a user interface element E that is user alterable, or not + §12.1.2 The Mutability Pseudo-classes: :read-only and :read-write + 3-UI/4 +
E:placeholder-shown + an input control currently showing placeholder text + §12.1.2 The Mutability Pseudo-classes: :read-only and :read-write + 3-UI/4 +
E:default + a user interface element E that is the default item in a group of related choices + §12.1.4 The Default-option Pseudo-class: :default + 3-UI/4 +
E:checked + a user interface element E that is checked/selected + (for instance a radio-button or checkbox) + §12.2.1 The Selected-option Pseudo-class: :checked + 3 +
E:indeterminate + a user interface element E that is in an indeterminate state + (neither checked nor unchecked) + §12.2.2 The Indeterminate-value Pseudo-class: :indeterminate + 4 +
E:valid
E:invalid +
a user-input element E that meets, or doesn’t, its data validity semantics + §12.3.2 The Range Pseudo-classes: :in-range and :out-of-range + 3-UI/4 +
E:in-range
E:out-of-range +
a user-input element E whose value is in-range/out-of-range + §12.3.2 The Range Pseudo-classes: :in-range and :out-of-range + 3-UI/4 +
E:required
E:optional +
a user-input element E that requires/does not require input + §12.3.3 The Optionality Pseudo-classes: :required and :optional + 3-UI/4 +
E:user-invalid + a user-altered user-input element E with incorrect input (invalid, out-of-range, omitted-but-required) + §12.3.4 The User-interaction Pseudo-class: :user-invalid + 4 +
E:root + an E element, root of the document + §13 Tree-Structural pseudo-classes + 3 +
E:empty + an E element that has no children (not even text nodes) + §13 Tree-Structural pseudo-classes + 3 +
E:blank + an E element that has no content except maybe white space + §13 Tree-Structural pseudo-classes + 4 +
E:nth-child(n [of S]?) + an E element, the n-th child of its parent matching S + §13.4 Child-indexed Pseudo-classes + 3/4 +
E:nth-last-child(n [of S]?) + an E element, the n-th child of its parent matching S, + counting from the last one + §13.4 Child-indexed Pseudo-classes + 3/4 +
E:first-child + an E element, first child of its parent + §13.4 Child-indexed Pseudo-classes + 2 +
E:last-child + an E element, last child of its parent + §13.4 Child-indexed Pseudo-classes + 3 +
E:only-child + an E element, only child of its parent + §13.4 Child-indexed Pseudo-classes + 3 +
E:nth-of-type(n) + an E element, the n-th sibling of its type + §13.5 Typed Child-indexed Pseudo-classes + 3 +
E:nth-last-of-type(n) + an E element, the n-th sibling of its type, + counting from the last one + §13.5 Typed Child-indexed Pseudo-classes + 3 +
E:first-of-type + an E element, first sibling of its type + §13.5 Typed Child-indexed Pseudo-classes + 3 +
E:last-of-type + an E element, last sibling of its type + §13.5 Typed Child-indexed Pseudo-classes + 3 +
E:only-of-type + an E element, only sibling of its type + §13.5 Typed Child-indexed Pseudo-classes + 3 +
E F + an F element descendant of an E element + §14.1 Descendant combinator ( ) + 1 +
E > F + an F element child of an E element + §14.2 Child combinator (>) + 2 +
E + F + an F element immediately preceded by an E element + §14.3 Next-sibling combinator (+) + 2 +
E ~ F + an F element preceded by an E element + §14.4 Subsequent-sibling combinator (~) + 3 +
F || E + an E element that represents a cell in a grid/table + belonging to a column represented by an element F + §15 Grid-Structural Selectors + 4 +
E:nth-col(n) + an E element that represents a cell belonging to the nth column in a grid/table + §15 Grid-Structural Selectors + 4 +
E:nth-last-col(n) + an E element that represents a cell belonging to the nth column in a grid/table, counting from the last one + §15 Grid-Structural Selectors + 4 +
+

Note: Some Level 4 selectors (noted above as "3-UI") were introduced in [CSS3UI].

+

2.1. Live vs Snapshot Selector Profiles

+

Selectors are used in many different contexts, + with wildly varying performance characteristics. + Some powerful selectors are unfortunately too slow + to realistically include in the more performance-sensitive contexts. + To accommodate this, two profiles of the Selectors spec are defined:

+
+
live profile +
+ The live profile is appropriate for use in any context, + including browser CSS selector matching, which is live. + It includes every selector defined in this document, + except for: + +
snapshot profile +
The snapshot profile is appropriate for contexts which aren’t extremely performance sensitive; + in particular, it’s appropriate for contexts which evaluate selectors against a static document tree. + For example, the query() method defined in [DOM] should use the snapshot profile. + It includes all of the selectors defined in this document. +
+

CSS implementations conformant to Selectors Level 4 must use the live profile for CSS selection. + Implementations using the live profile must treat selectors that are not included in the profile + as unknown and invalid.

+

The categorization of things into the “live” or snapshot profiles needs implementor review. + If some things currently not in the live profile can reasonably be done in CSS Selectors, + we should move them.

+

3. Selector Syntax and Structure

+

3.1. Structure and Terminology

+

A selector represents + a particular pattern of element(s) in a tree structure. + The term selector can refer to a simple selector, compound selector, complex selector, or selector list. + The subject of a selector is + any element that selector is defined to be about; + that is, any element matching that selector.

+

A simple selector is a single condition on an element. + A type selector, universal selector, attribute selector, class selector, ID selector, + or pseudo-class is a simple selector. + (It is represented by <simple-selector> in the selectors grammar.) + A given element is said to match a simple selector when that simple selector, + as defined in this specification and in accordance with the document language, + accurately describes the element.

+

A compound selector is a sequence of simple selectors that are not separated by a combinator, + and represents a set of simultaneous conditions on a single element. + If it contains a type selector or universal selector, + that selector must come first in the sequence. + Only one type selector or universal selector is allowed in the sequence. + (A compound selector is represented by <compound-selector> in the selectors grammar.) + A given element is said to match a compound selector when it matches all simple selectors in the compound selector.

+

Note: As whitespace represents the descendant combinator, + no whitespace is allowed between the simple selectors in a compound selector.

+

A combinator is a condition of relationship between two elements + represented by the compound selectors on either side. + Combinators in Selectors Level 4 include: + the descendant combinator (white space), + the child combinator (U+003E, >), + the next-sibling combinator (U+002B, +), + and the subsequent-sibling combinator (U+007E, ~). + Two given elements are said to match a combinator when the condition of relationship between these elements is true.

+

A complex selector is + a sequence of one or more compound selectors separated by combinators. + It represents a set of simultaneous conditions + on a set of elements in the particular relationships + described by its combinators. + (Complex selectors are represented by <complex-selector> in the selectors grammar.) + A given element is said to match a complex selector when there exists a list of elements, + each matching a corresponding compound selector in the complex selector, + with their relationships matching the combinators between them, + and with the given element matching the last compound selector.

+

Note: Thus, a selector consisting of a single compound selector matches any element satisfying the requirements + of its constituent simple selectors. + Prepending another compound selector and a combinator to a sequence imposes additional matching constraints, + such that the subjects of a complex selector are always + a subset of the elements represented by its last compound selector.

+

A list of simple/compound/complex selectors is a comma-separated list of simple, compound, + or complex selectors. + This is also called just a selector list when the type is either unimportant or specified in the surrounding prose; + if the type is important and unspecified, + it defaults to meaning a list of complex selectors. + (See §4.1 Selector Lists for additional information on selector lists and the various <*-selector-list> productions in the grammar for their formal syntax.) + A given element is said to match a selector list when it matches any (at least one) of the selectors in that selector list.

+

Pseudo-elements aren’t handled here, and should be.

+

3.2. Data Model

+

Selectors are evaluated against an element tree such as the DOM. [DOM] Within this specification, + this may be referred to as the "document tree" or "source document".

+

Each element may have any of the following five aspects, + which can be selected against, + all of which are matched as strings:

+
    +
  • The element’s type (also known as its tag name). +
  • The element’s namespace. +
  • An ID. +
  • Classes (named groups) to which it belongs. +
  • Attributes, which are name-value pairs. +
+

While individual elements may lack any of the above features, + some elements are featureless. + A featureless element does not match any selector at all, + except those it is explicitly defined to match. + If a given selector is allowed to match a featureless element, + it must do so while ignoring the default namespace. [CSS3NAMESPACE]

+
For example, the shadow host in a shadow tree is featureless, + and can’t be matched by any pseudo-class except for :host and :host-context().)
+

Many of the selectors depend on the semantics of the document language (i.e. the language and semantics of the document tree) + and/or the semantics of the host language (i.e. the language that is using selectors syntax). + For example, the :lang() selector depends on the document language (e.g. HTML) + to define how an element is associated with a language. + As a slightly different example, the ::first-line pseudo-element + depends on the host language (e.g. CSS) + to define what a ::first-line pseudo-element represents + and what it can do.

+

3.3. Scoped Selectors

+

Some host applications may choose to scope selectors + to a particular subtree or fragment of the document. + The root of the scoping subtree is called the scoping root, + and may be either a true element (the scoping element) + or a virtual one (such as a DocumentFragment).

+

When a selector is scoped, + it matches an element only if the element is a descendant of the scoping root. + (The rest of the selector can match unrestricted; + it’s only the final matched elements that must be within the scope.)

+
+ For example, + the element.querySelector() function defined in [DOM] allows the author to evaluate a scoped selector + relative to the element it’s called on. +

A call like widget.querySelector("a") will thus only find a elements inside of the widget element, + ignoring any other as that might be scattered throughout the document.

+
+

Note: If the context does not explicitly define any :scope elements for the selector, + the scoping root is a :scope element.

+

3.4. Relative Selectors

+

Certain contexts may accept relative selectors, + which are a shorthand for selectors that represent elements relative to a :scope element (i.e. an element that matches :scope). + In a relative selector, + “:scope ” (the :scope pseudo-class followed by a space) + is implied at the beginning of each complex selector that does not already contain the :scope pseudo-class. + This allows the selector to begin syntactically with a combinator. + However, it must be absolutized before matching.

+

Relative selectors, once absolutized, + can additionally be scoped.

+

Relative selectors are represented by <relative-selector> in the selectors grammar.

+

3.4.1. Absolutizing a Relative Selector

+

To absolutize a relative selector:

+

If there are no :scope elements and the selector is scoped to a virtual scoping root:

+

This needs a sane definition.

+

Otherwise:

+
    +
  1. If the selector starts with a combinator other than the white space form of the descendant combinator, + prepend :scope as the initial compound selector. +
  2. Otherwise, if the selector does not contain any instance of the :scope pseudo-class + (either at the top-level or as an argument to a functional pseudo-class), + prepend :scope followed by the white space form of the descendant combinator. +
  3. Otherwise, the selector is already absolute. +
+

To absolutize a relative selector list, + absolutize each relative selector in the list.

+

3.5. Pseudo-classes

+

Pseudo-classes are simple selectors that permit selection based on + information that lies outside of the document tree + or that can be awkward or impossible to express using the other simple selectors. + They can also be dynamic, + in the sense that an element can acquire or lose a pseudo-class + while a user interacts with the document, + without the document itself changing. Pseudo-classes do not appear in or modify the document source or document tree.

+

The syntax of a pseudo-class consists of a ":" (U+003A COLON) + followed by the name of the pseudo-class as a CSS identifier, + and, in the case of a functional pseudo-class, + a pair of parentheses containing its arguments.

+

For example, :valid is a regular pseudo-class, + and :lang() is a functional pseudo-class.

+

Like all CSS keywords, pseudo-class names are ASCII case-insensitive. + No white space is allowed between the colon and the name of the pseudo-class, + nor, as usual for CSS syntax, + between a functional pseudo-class’s name and its opening parenthesis + (which thus form a CSS function token). + Also as usual, white space is allowed around the arguments inside the parentheses + of a functional pseudo-class + unless otherwise specified.

+

Like other simple selectors, pseudo-classes are allowed in all compound selectors contained in a selector, + and must follow the type selector or universal selector, if present.

+

Note: Some pseudo-classes are mutually exclusive + (such that a compound selector containing them, while valid, will never match anything), + while others can apply simultaneously to the same element.

+

3.6. Pseudo-elements

+

Similar to how certain pseudo-classes represent additional state information + not directly present in the document tree, + a pseudo-element represents an element + not directly present in the document tree. + They are used to create abstractions about the document tree + beyond those provided by the document tree. + For example, + pseudo-elements can be used to select portions of the document + that do not correspond to a document-language element + (including such ranges as don’t align to element boundaries or fit +within its tree structure); + that represent content not in the document tree or in an alternate +projection of the document tree; + or that rely on information provided by styling, layout, user +interaction, and other processes that are not reflected in the document +tree.

+
+ For instance, document languages do not offer mechanisms to access + the first letter or first line of an element’s content, + but there exist pseudo-elements (::first-letter and ::first-line) + that allow those things to be styled. + Notice especially that in the case of ::first-line, + which portion of content is represented by the pseudo-element + depends on layout information + that cannot be inferred from the document tree. +

Pseudo-elements can also represent content that doesn’t exist in the source document at all, + such as the ::before and ::after pseudo-elements + which allow additional content to be inserted before or after the contents of any element.

+
+

Like pseudo-classes pseudo-elements do not appear in or modify the document source or document tree. + Accordingly, they also do not affect the interpretation of structural pseudo-classes or other selectors pertaining to their originating element or its tree.

+

The host language defines which pseudo-elements exist, their type, and their abilities. + Pseudo-elements that exist in CSS + are defined in [CSS21] (Level 2), [SELECT] (Level 3), and [CSS-PSEUDO-4] (Level 4).

+

3.6.1. Syntax

+

The syntax of a pseudo-element is "::" (two U+003A COLON characters) + followed by the name of the pseudo-element as an identifier. Pseudo-element names are ASCII case-insensitive. + No white space is allowed between the two colons, or between the colons and the name.

+

Because CSS Level 1 and CSS Level 2 conflated pseudo-elements and pseudo-classes by sharing a single-colon syntax for both, + user agents must also accept the previous one-colon notation + for the Level 1 & 2 pseudo-elements + (::before, ::after, ::first-line, and ::first-letter). + This compatibility notation is not allowed any other pseudo-elements. + However, as this syntax is deprecated, + authors should use the Level 3+ double-colon syntax for these pseudo-elements.

+

Pseudo-elements are featureless, + and so can’t be matched by any other selector.

+

3.6.2. Binding to the Document Tree

+

Pseudo-elements do not exist independently in the tree: + they are always bound to another element on the page, + called their originating element. + Syntactically, a pseudo-element immediately follows + the compound selector representing its originating element. + If this compound selector is omitted, + it is assumed to be the universal selector *.

+
+ For example, in the selector div a::before, + the a elements matched by the selector are the originating elements for the ::before pseudo-elements attached to them. +

The selector ::first-line is equivalent to *::first-line, + which selects the ::first-line pseudo-element on every element in the document.

+
+

When a pseudo-element is encountered in a selector, + the part of the selector before the pseudo-element selects the originating element for the pseudo-element; + the part of the selector after it, if any, applies to the pseudo-element itself. + (See below.)

+

3.6.3. Pseudo-classing Pseudo-elements

+

A pseudo-element may be immediately followed + by any combination of the user action pseudo-classes, + in which case the pseudo-element is represented only when it is in the corresponding state. + Whether these pseudo-classes can match on the pseudo-element depends on the pseudo-class and pseudo-element’s definitions: + unless otherwise-specified, none of these pseudo-classes will match on the pseudo-element.

+

Clarify that :not() and :matches() can be used when containing above-mentioned pseudos.

+
+ For example, since the :hover pseudo-class specifies + that it can apply to any pseudo-element, ::first-line:hover will match when the first line is hovered. + However, since neither :focus nor ::first-line define that :focus can apply to ::first-line, + the selector ::first-line:focus will never match anything. +

Does ::first-line:not(:focus) match anything?

+

Notice that ::first-line:hover is very different from :hover::first-line, + which matches the first line of any originating element that is hovered! + For example, :hover::first-line also matches the first line of a paragraph + when the second line of the paragraph is hovered, + whereas ::first-line:hover only matches if the first line itself is hovered.

+
+

Note: Note that, unless otherwise specified in a future specification, + pseudo-classes other than the user action pseudo-classes are not valid when compounded to a pseudo-element; + so, for example, ::before:first-child is an invalid selector.

+

3.6.4. Internal Structure

+

Some pseudo-elements are defined to have internal structure. + These pseudo-elements may be followed by child/descendant combinators + to express those relationships. + Selectors containing combinators after the pseudo-element + are otherwise invalid.

+
For example, ::first-letter + span and ::first-letter em are invalid selectors. + However, since ::shadow is defined to have internal structure, ::shadow > p is a valid selector.
+

Note: A future specification may expand the capabilities of existing pseudo-elements, + so some of these currently-invalid selectors (e.g. ::first-line :any-link) + may become valid in the future.

+

The children of such pseudo-elements can simultaneously be children of other elements, too. + However, at least in CSS, their rendering must be defined so as to maintain the tree-ness of the box tree.

+
+ For example, + the ::content pseudo-element treats elements distributed to it as its children. + This means that, given the following fragment: +
<div>
+  <span>foo</span>
+  <"shadow root">
+    <content></content>
+  </"shadow root">
+</div>
+
+

the selectors div > span and div::shadow ::content > span select the same element via different paths.

+

However, when rendered, + the <span> element generates boxes as if it were the child of the <content> element, + rather than the <div> element, + so the tree structure of the box tree is maintained.

+
+

3.7. Characters and case sensitivity

+

All Selectors syntax is case-insensitive within the ASCII range + (i.e. [a-z] and [A-Z] are equivalent), + except for the parts + that are not under the control of Selectors: + specifically, + the case-sensitivity of + document language element names, + attribute names, + and attribute values + depends on the document language.

+
For example, in HTML, element and attribute names are ASCII case-insensitive, + but in XML, they are case-sensitive.
+

Case sensitivity of namespace prefixes is defined in [CSS3NAMESPACE]. + Case sensitivity of language ranges is defined in the :lang() section.

+

White space in Selectors consists of the + code points SPACE (U+0020), TAB (U+0009), LINE FEED (U+000A), + CARRIAGE RETURN (U+000D), and FORM FEED (U+000C). + Other space-like code points, such as EM SPACE (U+2003) and + IDEOGRAPHIC SPACE (U+3000), are never considered syntactic white space.

+

Code points in Selectors can be escaped with a backslash + according to the same escaping rules as CSS. [CSS21] Note that escaping a code point “cancels out” + any special meaning it may have in Selectors. + For example, the selector #foo>a contains a combinator, + but #foo\>a instead selects an element with the id foo>a.

+

3.8. Declaring Namespace Prefixes

+

Certain selectors support namespace prefixes. + The mechanism by which namespace prefixes are declared should be specified by the language that uses Selectors. + If the language does not specify a namespace prefix declaration mechanism, + then no prefixes are declared. + In CSS, namespace prefixes are declared with the @namespacerule. [CSS3NAMESPACE]

+

3.9. Invalid Selectors and Error Handling

+

User agents must observe the rules for handling invalid selectors:

+
    +
  • a parsing error in a selector, + e.g. an unrecognized token or a token which is not allowed at the current parsing point + (see §17 Grammar), + causes that selector to be invalid. +
  • a simple selector containing an undeclared namespace prefix is invalid +
  • a selector containing an invalid simple selector, an invalid combinator + or an invalid token is invalid. +
  • a selector list containing an invalid selector is invalid. +
  • an empty selector, i.e. one that contains no compound selector, is invalid. +
+

Note: Consistent with CSS’s forwards-compatible parsing principle, + UAs must treat as invalid any pseudo-classes, pseudo-elements, combinators, or other syntactic constructs + for which they have no usable level of support. + See Partial Implementations.

+

An invalid selector represents, and therefore matches, nothing.

+

4. Logical Combinations

+

4.1. Selector Lists

+

A comma-separated list of selectors represents the union of all + elements selected by each of the individual selectors in the selector list. + (A comma is U+002C.) For example, in CSS when several selectors share + the same declarations, they may be grouped into a comma-separated + list. White space may appear before and/or after the comma.

+
+ CSS example: + In this example, we condense three rules with identical + declarations into one. Thus, +
h1 { font-family: sans-serif }
+h2 { font-family: sans-serif }
+h3 { font-family: sans-serif }
+
+

is equivalent to:

+
h1, h2, h3 { font-family: sans-serif }
+
+
+

Warning: the equivalence is true in this example + because all the selectors are valid selectors. If just one of these + selectors were invalid, the entire selector list would be + invalid. This would invalidate the rule for all three heading + elements, whereas in the former case only one of the three individual + heading rules would be invalidated.

+
+ Invalid CSS example: +
h1 { font-family: sans-serif }
+h2..foo { font-family: sans-serif }
+h3 { font-family: sans-serif }
+
+

is not equivalent to:

+
h1, h2..foo, h3 { font-family: sans-serif } 
+

because the above selector (h1, h2..foo, h3) + is entirely invalid and the entire style rule is dropped. (When + the selectors are not grouped, only the rule for h2..foo is dropped.)

+
+

4.2. The Matches-any Pseudo-class: :matches()

+

The matches-any pseudo-class, :matches(), + is a functional pseudo-class taking a selector list as its argument. + It represents an element that is represented by its argument.

+

Note: The specificity of the :matches() pseudo-class + is replaced by the specificity of its argument. + Thus, a selector written with :matches() has equivalent specificity + to the equivalent selector written without :matches() For example, :matches(ul, ol, .list) > [hidden] and ul > [hidden], ol > [hidden], .list > [hidden] are equivalent in both their matching behavior and specificity. + See §16 Calculating a selector’s specificity. + ISSUE: See also issue 1027.

+

Pseudo-elements cannot be represented by the matches-any pseudo-class; + they are not valid within :matches().

+

Default namespace declarations do not affect the compound selector representing the subject of any selector + within a :matches() pseudo-class, + unless that compound selector contains + an explicit universal selector or type selector.

+

Why this exception for the explicit universal selector?

+
+ For example, the following selector matches any element that is being + hovered or focused, regardless of its namespace. In particular, it + is not limited to only matching elements in the default namespace + that are being hovered or focused. +
*|*:matches(:hover, :focus) 
+

The following selector, however, represents only hovered or focused + elements that are in the default namespace, because it uses an explicit + universal selector within the :matches() notation:

+
*|*:matches(*:hover, *:focus) 
+
+

4.3. The Negation Pseudo-class: :not()

+

The negation pseudo-class, :not(), + is a functional pseudo-class taking a selector list as an argument. + It represents an element that is not represented by its argument.

+

Note: In Selectors Level 3, + only a single simple selector was allowed as the argument to :not().

+

Note: The specificity of the :not() pseudo-class + is replaced by the specificity of the most specific selector in its argument; + thus it has the exact behavior of :not(:matches(argument)). + See §16 Calculating a selector’s specificity.

+

Pseudo-elements cannot be represented by the negation pseudo-class; + they are not valid within :not().

+
+ For example, the following selector matches all button elements in an HTML document + that are not disabled. +
button:not([DISABLED]) 
+

The following selector represents all but FOO elements.

+
*:not(FOO)
+

The following compound selector represents all HTML elements + except links.

+
html|*:not(:link):not(:visited)
+
+

As with :matches(), + default namespace declarations do not affect the compound selector representing the subject of any selector + within a :not() pseudo-class, + unless that compound selector contains + an explicit universal selector or type selector. + (See :matches() for examples.)

+

Note: The :not() pseudo-class allows useless selectors to be written. + For instance :not(*|*), which represents no element at all, + or div:not(span), which is equivalent to div but with a higher specificity.

+

4.4. The Specificity-adjustment Pseudo-class: :something()

+

The Specificity-adjustment pseudo-class, :something(), + is a functional pseudo-class + with the same syntax and functionality as :matches(). + Unlike :matches(), neither the :something pseudo-class, nor any of its arguments + contribute to the specificity of the selector—its specificity is always zero.

+

This is useful for introducing filters in a selector + while keeping the associated style declarations easy to override.

+

This pseudo-class needs a name. See previous discussion, open issue.

+
+ Below is a common example where the specificity heuristic fails + to match author expectations: +
a:not(:hover) {
+  text-decoration: none;
+}
+
+nav a {
+  /* Has no effect */
+  text-decoration: underline;
+}
+
+

However, by using :something() the author can explicitly declare their intent:

+
a:something(:not(:hover)) {
+  text-decoration: none;
+}
+
+nav a {
+  /* Works now! */
+  text-decoration: underline;
+}
+
+
+

Note: Future levels of Selectors may introduce an additional argument + to explicitly set the specificity of that instance of the pseudo-class.

+

4.5. The Relational Pseudo-class: :has()

+

The relational pseudo-class, :has(), + is a functional pseudo-class taking a relative selector list as an argument. + It represents an element if any of the relative selectors, + when absolutized and evaluated with the element as the :scope elements, + would match at least one element.

+
+ For example, the following selector matches only <a> elements that contain an <img> child: +
a:has(> img)
+

The following selector matches a <dt> element + immediately followed by another <dt> element:

+
dt:has(+ dt)
+

The following selector matches <section> elements + that don’t contain any heading elements:

+
section:not(:has(h1, h2, h3, h4, h5, h6))
+

Note that ordering matters in the above selector. + Swapping the nesting of the two pseudo-classes, like:

+
section:has(:not(h1, h2, h3, h4, h5, h6))
+

...would result matching any <section> element + which contains anything that’s not a header element.

+
+

5. Elemental selectors

+

5.1. Type (tag name) selector

+

A type selector is the name of a document language element type, + and represents an instance of that element type in the document tree.

+
For example, the selector h1 represents an h1 element in the document.
+

A type selector is written as a CSS qualified name: + an identifier with an optional namespace prefix. [CSS3NAMESPACE] (See §5.3 Namespaces in Elemental Selectors.)

+

5.2. Universal selector

+

The universal selector is a special type selector, + that represents an element of any element type.

+

It is written a CSS qualified name with an asterisk (* U+002A) as the local name. + Like a type selector, + the universal selector can be qualified by a namespace, + restricting it to only elements belonging to that namespace, + and is affected by a default namespace as defined in §5.3 Namespaces in Elemental Selectors.

+

Unless an element is featureless, + the presence of a universal selector has no effect on whether the element matches the selector. + (Featureless elements do not match any selector, + including the universal selector.)

+
+ +
    +
  • *[hreflang|=en] and [hreflang|=en] are equivalent, +
  • *.warning and .warning are equivalent, +
  • *#myid and #myid are equivalent. +
+
+

The universal selector follows the same syntax rules as other type selectors: + only one can appear per compound selector, + and it must be the first simple selector in the compound selector.

+

Note: In some cases, adding a universal selector can make a selector easier to read, + even though it has no effect on the matching behavior. + For example, div :first-child and div:first-child are somewhat difficult to tell apart at a quick glance, + but writing the former as div *:first-child makes the difference obvious.

+

5.3. Namespaces in Elemental Selectors

+

Type selectors and universal selectors allow an optional namespace component: + a namespace prefix that has been previously declared may be prepended to the element name separated by the namespace separator “vertical bar” (| U+007C). + (See, e.g., [XML-NAMES] for the use of namespaces in XML.) + It has the following meaning in each form:

+
+
ns|E +
elements with name E in namespace ns +
*|E +
elements with name E in any namespace, + including those without a namespace +
|E +
elements with name E without a namespace +
E +
if no default namespace has been declared for selectors, + this is equivalent to *|E. + Otherwise it is equivalent to ns|E + where ns is the default namespace. +
+
+ CSS examples: +
@namespace foo url(http://www.example.com);
+foo|h1 { color: blue }  /* first rule */
+foo|* { color: yellow } /* second rule */
+|h1 { color: red }      /* ...*/
+*|h1 { color: green }
+h1 { color: green }
+
+

The first rule (not counting the @namespace at-rule) + will match only h1 elements in the + "http://www.example.com" namespace.

+

The second rule will match all elements in the + "http://www.example.com" namespace.

+

The third rule will match only h1 elements with + no namespace.

+

The fourth rule will match h1 elements in any + namespace (including those without any namespace).

+

The last rule is equivalent to the fourth rule because no default + namespace has been defined.

+
+

If a default namespace is declared, compound selectors without type selectors in them + still only match elements in that default namespace.

+
+ For example, + in the following style sheet: +
@namespace url("http://example.com/foo");
+
+.special { ... }
+
+

The .special selector only matches elements in the "http://example.com/foo" namespace, + even though no reference to the type name (which is paired with the namespace in the DOM) appeared.

+
+

A type selector or universal selector containing a namespace prefix + that has not been previously declared is an invalid selector.

+

6. Attribute selectors

+

Selectors allow the representation of an element’s attributes. When + a selector is used as an expression to match against an element, + an attribute selector must be considered to match an element if that + element has an attribute that matches the attribute represented by the + attribute selector.

+

Add comma-separated syntax for multiple-value matching? + e.g. [rel ~= next, prev, up, first, last]

+

6.1. Attribute presence and value selectors

+

CSS2 introduced four attribute selectors:

+
+
[att] +
Represents an element with the att attribute, + whatever the value of the attribute. +
[att=val] +
Represents an element with the att attribute + whose value is exactly "val". +
[att~=val] +
Represents an element with the att attribute + whose value is a whitespace-separated list of words, + one of which is exactly "val". + If "val" contains whitespace, + it will never represent anything + (since the words are separated by spaces). + Also if "val" is the empty string, + it will never represent anything. +
[att|=val] +
Represents an element with the att attribute, + its value either being exactly "val" + or beginning with "val" immediately followed by "-" (U+002D). + This is primarily intended to allow language subcode matches + (e.g., the hreflang attribute on the a element in HTML) + as described in BCP 47 ([BCP47]) or its successor. + For lang (or xml:lang) language subcode matching, + please see the :lang pseudo-class. +
+

Attribute values must be <ident-token>s or <string-token>s. [CSS3SYN]

+
+ Examples: +

The following attribute selector represents an h1 element + that carries the title attribute, + whatever its value:

+
h1[title]
+

In the following example, the selector represents a span element whose class attribute has + exactly the value "example":

+
span[class="example"]
+

Multiple attribute selectors can be used to represent several + attributes of an element, or several conditions on the same + attribute. Here, the selector represents a span element + whose hello attribute has exactly the value "Cleveland" + and whose goodbye attribute has exactly the value + "Columbus":

+
span[hello="Cleveland"][goodbye="Columbus"]
+

The following CSS rules illustrate the differences between + "=" and "~=". The first selector would match, for example, an a element with the value "copyright copyleft + copyeditor" on a rel attribute. The second selector + would only match an a element with an href attribute having the exact value "http://www.w3.org/".

+
a[rel~="copyright"] { ... }
+a[href="http://www.w3.org/"] { ... }
+
+

The following selector represents an a element + whose hreflang attribute is exactly "fr".

+
a[hreflang=fr] 
+

The following selector represents an a element for + which the value of the hreflang attribute begins with + "en", including "en", "en-US", and "en-scouse":

+
a[hreflang|="en"] 
+

The following selectors represent a DIALOGUE element + whenever it has one of two different values for an attribute character:

+
DIALOGUE[character=romeo]
+DIALOGUE[character=juliet]
+
+
+

6.2. Substring matching attribute selectors

+

Three additional attribute selectors are provided for matching + substrings in the value of an attribute:

+
+
[att^=val] +
Represents an element with the att attribute + whose value begins with the prefix "val". + If "val" is the empty string + then the selector does not represent anything. +
[att$=val] +
Represents an element with the att attribute + whose value ends with the suffix "val". + If "val" is the empty string + then the selector does not represent anything. +
[att*=val] +
Represents an element with the att attribute + whose value contains at least one instance of the substring "val". + If "val" is the empty string + then the selector does not represent anything. +
+

Attribute values must be <ident-token>s or <string-token>s.

+
+ Examples: + The following selector represents an HTML object element, + referencing an image: +
object[type^="image/"] 
+

The following selector represents an HTML a element + with an href attribute whose value ends with ".html".

+
a[href$=".html"] 
+

The following selector represents an HTML paragraph + with a title attribute whose value contains the substring "hello"

+
p[title*="hello"] 
+
+

6.3. Case-sensitivity

+

By default case-sensitivity of attribute names and values in selectors + depends on the document language. To match attribute values case-insensitively + regardless of document language rules, the attribute selector may include the + identifier i before the closing bracket (]). + When this flag is present, UAs must match the attribute’s value + case-insensitively within the ASCII range. + Like the rest of Selectors syntax, + the i identifier is case-insensitive within the ASCII range.

+
+ The following rule will style the frame attribute when it + has a value of hsides, whether that value is represented + as hsides, HSIDES, hSides, etc. + even in an XML environment where attribute values are case-sensitive. +
[frame=hsides i] { border-style: solid none; } 
+
+

6.4. Attribute selectors and namespaces

+

The attribute name in an attribute selector is given as a CSS qualified + name: a namespace prefix that has been previously declared may be prepended to the attribute name separated by the namespace + separator "vertical bar" (|). In keeping with + the Namespaces in the XML recommendation, default namespaces do not + apply to attributes, therefore attribute selectors without a namespace + component apply only to attributes that have no namespace (equivalent + to |attr). An asterisk may be used for + the namespace prefix indicating that the selector is to match all + attribute names without regard to the attribute’s namespace.

+

An attribute selector with an attribute name containing a namespace + prefix that has not been previously declared is + an invalid selector.

+
+ CSS examples: +
@namespace foo "http://www.example.com";
+[foo|att=val] { color: blue }
+[*|att] { color: yellow }
+[|att] { color: green }
+[att] { color: green }
+
+

The first rule will match only elements with the attribute att in the "http://www.example.com" namespace with the + value "val".

+

The second rule will match only elements with the attribute att regardless of the namespace of the attribute + (including no namespace).

+

The last two rules are equivalent and will match only elements + with the attribute att where the attribute is not + in a namespace.

+
+

6.5. Default attribute values in DTDs

+

Attribute selectors represent attribute values in the document tree. + How that document tree is constructed is outside the scope of Selectors. + In some document formats default attribute values can be defined in a DTD or + elsewhere, but these can only be selected by attribute selectors if they + appear in the document tree. Selectors should be designed so that they + work whether or not the default values are included in the document tree.

+

For example, a XML UA may, but is not required to, + read an “external subset” of the DTD, but is required to + look for default attribute values in the document’s “internal subset”. + (See, e.g., [XML10] for definitions of these subsets.) + Depending on the UA, a default attribute value defined in the external subset of the DTD + might or might not appear in the document tree.

+

A UA that recognizes an XML namespace may, but is not required to use its + knowledge of that namespace to treat default attribute values as if + they were present in the document. (For example, an XHTML UA is not + required to use its built-in knowledge of the XHTML DTD. See, e.g., [XML-NAMES] for details on namespaces in XML + 1.0.)

+

Note: Typically, implementations + choose to ignore external subsets. This corresponds to the behavior + of non-validating processors as defined by the XML specification.

+
+ Example: +

Consider an element EXAMPLE with an attribute radix that has a default value of "decimal". The DTD fragment might be

+
<!ATTLIST EXAMPLE radix (decimal,octal) "decimal"> 
+

If the style sheet contains the rules

+
EXAMPLE[radix=decimal] { /*... default property settings ...*/ }
+EXAMPLE[radix=octal]   { /*... other settings...*/ }
+
+

the first rule might not match elements whose radix attribute is + set by default, i.e. not set explicitly. To catch all cases, the + attribute selector for the default value must be dropped:

+
EXAMPLE                { /*... default property settings ...*/ }
+EXAMPLE[radix=octal]   { /*... other settings...*/ }
+
+

Here, because the selector ''EXAMPLE[radix=octal]'' is + more specific than the type selector alone, the style declarations in + the second rule will override those in the first for elements that + have a radix attribute value of "octal". Care has to be taken that + all property declarations that are to apply only to the default case + are overridden in the non-default cases' style rules.

+
+

6.6. Class selectors

+

The class selector is given as a full stop (. U+002E) immediately + followed by an identifier. It represents an element belonging to the + class identified by the identifier, as defined by the document language. + For example, in [HTML5], [SVG11], and [MATHML] membership in a + class is given by the class attribute: in these languages + it is equivalent to the ~= notation applied to the + local class attribute + (i.e. [class~=identifier]).

+
+ CSS examples: +

We can assign style information to all elements with class~="pastoral" as follows:

+
*.pastoral { color: green }  /* all elements with class~=pastoral */ 
+

or just

+
.pastoral { color: green }  /* all elements with class~=pastoral */ 
+

The following assigns style only to H1 elements with class~="pastoral":

+
H1.pastoral { color: green }  /* H1 elements with class~=pastoral */ 
+

Given these rules, the first H1 instance below would not have + green text, while the second would:

+
<H1>Not green</H1>
+<H1 class="pastoral">Very green</H1>
+
+

The following rule matches any P element whose class attribute has been assigned a list of whitespace-separated values that includes both pastoral and marine:

+
p.pastoral.marine { color: green } 
+

This rule matches when class="pastoral blue aqua + marine" but does not match for class="pastoral + blue".

+
+

Note: Because CSS gives considerable + power to the "class" attribute, authors could conceivably design their + own "document language" based on elements with almost no associated + presentation (such as div and span in HTML) + and assigning style + information through the "class" attribute. Authors should avoid this + practice since the structural elements of a document language often + have recognized and accepted meanings and author-defined classes may + not.

+

Note: If an element has multiple + class attributes, their values must be concatenated with spaces + between the values before searching for the class. As of this time the + working group is not aware of any manner in which this situation can + be reached, however, so this behavior is explicitly non-normative in + this specification.

+

When matching against a document which is in quirks mode, + class names must be matched ASCII case-insensitively; + class selectors are otherwise case-sensitive.

+

6.7. ID selectors

+

Document languages may contain attributes that are declared to be of type ID. + What makes attributes of type ID special + is that no two such attributes can have the same value in a conformant document, + regardless of the type of the elements that carry them; + whatever the document language, + an ID typed attribute can be used to uniquely identify its element. + In HTML all ID attributes are named id; + XML applications may name ID attributes differently, + but the same restriction applies. + Which attribute on an element is considered the “ID attribute“ is defined by the document language.

+

An ID selector consists of a “number sign” (U+0023, #) + immediately followed by the ID value, + which must be a CSS identifier. + An ID selector represents an element instance that has an identifier that matches the identifier in the ID selector. + (It is possible in non-conforming documents for multiple elements to match a single ID selector.)

+
+ Examples: + The following ID selector represents an h1 element + whose ID-typed attribute has the value "chapter1": +
h1#chapter1 
+

The following ID selector represents any element whose ID-typed + attribute has the value "chapter1":

+
#chapter1 
+

The following selector represents any element whose ID-typed + attribute has the value "z98y".

+
*#z98y 
+
+

Note: In XML 1.0 [XML10], the information about which attribute + contains an element’s IDs is contained in a DTD or a schema. When + parsing XML, UAs do not always read the DTD, and thus may not know + what the ID of an element is (though a UA may have namespace-specific + knowledge that allows it to determine which attribute is the ID + attribute for that namespace). If a style sheet author knows or + suspects that a UA may not know what the ID of an element is, he + should use normal attribute selectors instead: + ''[name=p371] instead of #p371''.

+

If an element has multiple ID attributes, all of them must be + treated as IDs for that element for the purposes of the ID + selector. Such a situation could be reached using mixtures of xml:id, + DOM3 Core, XML DTDs, and namespace-specific knowledge.

+

When matching against a document which is in quirks mode, + IDs must be matched ASCII case-insensitively; + ID selectors are otherwise case-sensitive.

+

7. Linguistic Pseudo-classes

+

7.1. The Directionality Pseudo-class: :dir()

+

The :dir() pseudo-class allows the author to write + selectors that represent an element based on its directionality + as determined by the document language. + For example, [HTML5] defines how to determine the directionality of an element, + based on a combination of the dir attribute, the surrounding text, and other factors. + As another example, the its:dir and dirRule element + of the Internationalization Tag Set [ITS20] are able to define the directionality of an element in [XML10].

+

The :dir() pseudo-class does not select based on stylistic + states—for example, the CSS direction property does not affect + whether it matches.

+

The pseudo-class :dir(ltr) represents an element that + has a directionality of left-to-right (ltr). The + pseudo-class :dir(rtl) represents an element that has + a directionality of right-to-left (rtl). The argument to :dir() must be a single identifier, otherwise the selector + is invalid. White space is optionally allowed between the identifier + and the parentheses. Values other than ltr and rtl are not invalid, but do not match anything. (If a + future markup spec defines other directionalities, then Selectors may + be extended to allow corresponding values.)

+

The difference between :dir(C) and ''[dir=C]'' + is that ''[dir=C]'' only performs a comparison against a given + attribute on the element, while the :dir(C) pseudo-class + uses the UAs knowledge of the document’s semantics to perform the + comparison. For example, in HTML, the directionality of an element + inherits so that a child without a dir attribute will have + the same directionality as its closest ancestor with a valid dir attribute. As another example, in HTML, + an element that matches ''[dir=auto]'' will match either :dir(ltr) or :dir(rtl) depending on the resolved + directionality of the elements as determined by its contents. [HTML5]

+

7.2. The Language Pseudo-class: :lang()

+

If the document language specifies how + the (human) content language of an element is determined, + it is possible to write selectors that + represent an element based on its content language. + The :lang() pseudo-class represents an element that + is in one of the languages listed in its argument. It accepts + a comma-separated list of one or more language ranges as its + argument. Each language range in :lang() must be a valid CSS <ident> or <string>. + (Language ranges containing asterisks, for example, + must be quoted as strings.)

+

Note: The content language of an element is defined by the document language. + For example, in HTML [HTML5], the content language is determined by a + combination of the lang attribute, information from meta elements, and possibly also the protocol (e.g. + from HTTP headers). XML languages can use the xml:lang attribute to indicate language information for an element. [XML10]

+

The element’s content language matches a language range if + its content language (normalized to BCP 47 syntax if necessary) + matches the given language range in an extended filtering operation per [RFC4647] Matching of Language Tags (section 3.3.2). + The matching is performed case-insensitively within the ASCII range. + The language range does not need to be a valid language code to + perform this comparison.

+

Note: It is recommended that + documents and protocols indicate language using codes from BCP 47 [BCP47] or its successor, and by means of xml:lang attributes in the + case of XML-based documents [XML10]. See "FAQ: Two-letter or three-letter language codes."

+
+ Examples: + The two following selectors represent an HTML document that is in + Belgian French or German. The two next selectors represent q quotations in an arbitrary element in Belgian French + or German. +
html:lang(fr-be)
+html:lang(de)
+:lang(fr-be) > q
+:lang(de) > q
+
+
+

Note: One difference between :lang(C) and the ''|='' operator + is that the ''|='' operator only performs a comparison against a given + attribute on the element, while the :lang(C) pseudo-class + uses the UAs knowledge of the document’s semantics to perform the + comparison.

+
+ In this HTML example, only the BODY matches + ''[lang|=fr]'' (because it has a LANG attribute) but both + the BODY and the P match :lang(fr) (because both are in + French). The P does not match the ''[lang|=fr]'' because it + does not have a LANG attribute. +
<body lang=fr>
+  <p>Je suis français.</p>
+</body>
+
+
+
+ Another difference between :lang(C) and the ''|='' operator + is that :lang(C) performs implicit wildcard matching. +

For example, :lang(de-DE) will match all of de-DE, de-DE-1996, de-Latn-DE, de-Latf-DE, de-Latn-DE-1996, + whereas of those ''[lang|=de-DE] will only match de-DE'' and de-DE-1996.

+

To perform wildcard matching on the first subtag (the primary language), + an asterisk must be used: *-CH will match all of de-CH, it-CH, fr-CH, and rm-CH.

+

To select against an element’s lang attribute value + using this type of language range match, + use both the attribute selector and language pseudo-class together, + e.g. [lang]:lang(de-DE).

+
+

Note: Wildcard language matching and comma-separated lists are new in Level 4.

+

8. Location Pseudo-classes

+ +

The :any-link pseudo-class represents an element + that acts as the source anchor of a hyperlink. + For example, in [HTML5], any a, area, or link elements with an href attribute + are hyperlinks, and thus match :any-link. + It matches an element if the element would match either :link or :visited, + and is equivalent to :matches(:link, :visited).

+ +

User agents commonly display unvisited hyperlinks differently from + previously visited ones. Selectors + provides the pseudo-classes :link and :visited to distinguish them:

+
    +
  • The :link pseudo-class applies to links that have + not yet been visited. +
  • The :visited pseudo-class applies once the link has + been visited by the user. +
+

After some amount of time, user agents may choose to return a + visited link to the (unvisited) :link state.

+

The two states are mutually exclusive.

+
+ The following selector represents links carrying class footnote and already visited: +
.footnote:visited 
+
+

Since it is possible for style sheet authors to abuse the :link and :visited pseudo-classes + to determine which sites a user has visited without the user’s consent, + UAs may treat all links as unvisited links + or implement other measures to preserve the user’s privacy + while rendering visited and unvisited links differently.

+ +

The :local-link pseudo-class + allows authors to style hyperlinks based on the users current location within a site. + It represents an element that is + the source anchor of a hyperlink whose target’s absolute URL + matches the element’s own document URL. + If the hyperlink’s target includes a fragment URL, + then the fragment URL of the current URL must also match; + if it does not, then the fragment URL portion of the current URL + is not taken into account in the comparison.

+
+ For example, the following rule prevents links targetting the + current page from being underlined when they are part of the + navigation list: +
nav :local-link { text-decoration: none; } 
+
+

Note: The current URL of a page can change as a result of user actions + such as activating a link targetting a different fragment within the same page; + or by use of the pushState API; + as well as by the more obvious actions of navigating to a different page + or following a redirect (which could be initiated by protocols such as HTTP, + markup instructions such as <meta http-equiv="...">, + or scripting instructions ). + UAs must ensure that :local-link, + as well as the :target and :target-within pseudo-classes below, + respond correctly to all such changes in state.

+

8.4. The Target Pseudo-class: :target

+

In some document languages, + the document’s URL can further point to specific elements within the document + via the URL’s fragment. + The elements pointed to in this way are the target elements of the document.

+
In HTML the fragment points to the element in the page with the same ID. + The url https://example.com/index.html#section2, + for example, + points to the element with id="section2" in the document at https://example.com/index.html.
+

The :target pseudo-class matches the document’s target elements. + If the document’s URL has no fragment identifier, then the document has no target elements.

+
+ Example: +
p.note:target 
+

This selector represents a p element of class note that is the target element of the referring + URL.

+
+
+ CSS example: + Here, the :target pseudo-class is used to make the + target element red and place an image before it, if there is one: +
:target { color : red }
+:target::before { content : url(target.png) }
+
+
+

8.5. The Target Container Pseudo-class: :target-within

+

The :target-within pseudo-class + applies to elements for which the :target pseudo class applies + as well as to an element whose descendant in the flat tree (including non-element nodes, such as text nodes) + matches the conditions for matching :target-within.

+

8.6. The Reference Element Pseudo-class: :scope

+

In some contexts, selectors can be matched with an explicit set of :scope elements. + This is is a (potentially empty) set of elements + that provide a reference point for selectors to match against, + such as that specified by the querySelector() call in [DOM].

+

The :scope pseudo-class represents any element that is a :scope element. + If the :scope elements are not explicitly specified, + but the selector is scoped and the scoping root is an element, + then :scope represents the scoping root; + otherwise, it represents the root of the document + (equivalent to :root). + Specifications intending for this pseudo-class to match specific elements + rather than the document’s root element + must define either a scoping root (if using scoped selectors) or an explicit set of :scope elements.

+

9. User Action Pseudo-classes

+

Interactive user interfaces sometimes change the rendering in response to user actions. + Selectors provides several user action pseudo-classes for the selection of an element the user is acting on. + (In non-interactive user agents, these pseudo-classes are valid, but never match any element.)

+

These pseudo-classes are not mutually exclusive. + An element can match several such pseudo-classes at the same time.

+
+ Examples: +
a:link    /* unvisited links */
+a:visited /* visited links */
+a:hover   /* user hovers */
+a:active  /* active links */
+
+

An example of combining dynamic pseudo-classes:

+
a:focus
+a:focus:hover
+
+

The last selector matches a elements that are in + the pseudo-class :focus and in the pseudo-class :hover.

+
+

Note: The specifics of hit-testing, + necessary to know when several of the pseudo-classes defined in this section apply, + are not yet defined, + but will be in the future.

+

9.1. The Pointer Hover Pseudo-class: :hover

+

The :hover pseudo-class applies + while the user designates an element with a pointing device, + but does not necessarily activate it. + For example, a visual user agent could apply this pseudo-class + when the cursor (mouse pointer) hovers over a box generated by the element. + Interactive user agents that cannot detect hovering due to hardware limitations + (e.g., a pen device that does not detect hovering) + are still conforming; + the selector will simply never match in such a UA.

+

An element also matches :hover if one of its descendants in the flat tree (including non-element nodes, such as text nodes) + matches the above conditions.

+

Document languages may define additional ways in which an element can match :hover. + For example, [HTML5] defines a labeled control element as matching :hover when its label is hovered.

+

Note: Since the :hover state can apply to an element + because its child is designated by a pointing device, + it is possible for :hover to apply + to an element that is not underneath the pointing device.

+

The :hover pseudo-class can apply to any pseudo-element.

+

9.2. The Activation Pseudo-class: :active

+

The :active pseudo-class applies while an element + is being activated by the user. For example, between the times the + user presses the mouse button and releases it. On systems with more + than one mouse button, :active applies only to the + primary or primary activation button (typically the "left" mouse + button), and any aliases thereof.

+

There may be document-language or implementation-specific limits on + which elements can become :active. + For example, [HTML5] defines a list of activatable elements.

+

An element also matches :active if one of its descendants in the flat tree (including non-element nodes, such as text nodes) + matches the above conditions.

+

Document languages may define additional ways in which an element can match :active.

+

Note: An element can be both :visited and :active (or :link and :active).

+

9.3. The Input Focus Pseudo-class: :focus

+

The :focus pseudo-class applies + while an element has the focus + (accepts keyboard or mouse events, or other forms of input).

+

There may be document language or implementation specific limits on + which elements can acquire :focus. + For example, [HTML] defines a list of focusable areas.

+

Document languages may define additional ways in which an element can match :focus, + except that the :focus pseudo class must not automatically propagate to the parent element—see :focus-within if matching on the parent is desired. + (It may still apply to the parent element + if made to propagate due to other mechanisms, + but not merely due to being the parent.)

+

There’s a desire from authors to propagate :focus from a form control to its associated label element; + the main objection seems to be implementation difficulty. + See CSSWG issue (CSS) and WHATWG issue (HTML).

+

9.4. The Focus-Indicated Pseudo-class: :focus-visible

+

The :focus-visible pseudo-class applies + while an element matches the :focus pseudo-class and the UA determines via heuristics + that the focus should be made evident on the element. + (Many browsers show a “focus ring” by default in this case.)

+
+ For example, UAs typically display focus indicators on text fields + any time they’re focused, + to draw attention to the fact that keyboard input will affect their contents. +

On the other hand, UAs typically only display focus indicators on buttons + when they were focused by a keyboard interaction + (such as tabbing through the document)—because it’s not always immediately obvious + where the focus has gone after such an interaction, + but is sufficiently self-evident when the button was focused + by more obviously-targetted interactions, + like clicking on the button with a mouse pointer.

+
+
+ Page authors should follow these guidelines + when deciding whether to use :focus or :focus-visible to style the focused state of an element: +
    +
  • +

    If the element has “native” focus indicator behavior +(such as text fields or buttons), +use :focus-visible.

    +
  • +

    Otherwise, if the element is emulating a text input, +or something else that is intended to receive keyboard interaction, +use :focus.

    +
  • +

    Otherwise, +use :focus-visible.

    +
+
+

When UAs choose to specially indicate focus on an element, + or whether they specially indicate focus at all, + is UA-dependent. + Different UAs, + the same UA on different operating systems, + or the same UA on the same OS, + but with different user settings, + can make different choices as to when an element matches :focus-visible.

+
+ The following guidelines are suggested heuristics + for choosing when to apply :focus-visible to elements without “native” focus indicator behavior: +
    +
  • +

    If the element received focus via a keyboard interaction, +including indirectly, +such as triggering a dialog +by pressing a button using the keyboard, +apply :focus-visible.

    +
  • +

    If a keyboard event occurs while an element is focused, +even if the element wasn’t focused by a keyboard interaction, +apply :focus-visible.

    +
+
+

9.5. The Focus Container Pseudo-class: :focus-within

+

The :focus-within pseudo-class + applies to any element for which the :focus pseudo class applies + as well as to an element whose descendant in the flat tree (including non-element nodes, such as text nodes) + matches the conditions for matching :focus.

+

9.6. The Drop Target Pseudo-class: :drop and :drop()

+

The :drop pseudo-class applies to all elements + that are drop targets, + as defined by the document language, + while the user is “dragging” + or otherwise conceptually carrying an item + to be “dropped”.

+

The :drop() functional pseudo-class is identical to :drop, + but allows additional filters to be specified that can exclude some drop targets. + Its syntax is:

+
:drop( [ active || valid || invalid ]? ) 
+

The keywords have the following meanings:

+
+
active +
The drop target is the current drop target for the drag operation. + That is, if the user were to release the drag, + it would be dropped onto this drop target. +
valid +
+ If the document language has a concept of “valid” and “invalid” drop targets, + this only matches if the drop target is valid for the object currently being dragged. + Otherwise, it matches all drop targets. +

For example, HTML’s dropzone attribute can specify that the drop target only accepts strings or files that are set to a given type.

+
invalid +
If the document language has a concept of “valid” and “invalid” drop targets, + this only matches if the drop target is invalid for the object currently being dragged. + Otherwise, it matches nothing. +
+

Multiple keywords can be combined in the argument, + representing only drop targets that satisfy all of the keywords. + For example, :drop(valid active) will match the active drop target if it’s valid, + but not if it’s invalid.

+

If no keywords are given in the argument, :drop() has the same meaning as :dropit matches every drop target.

+

Turn this scenario into an example.

+

10. Time-dimensional Pseudo-classes

+

These pseudo-classes classify elements with respect to the + currently-displayed or active position in some timeline, such as + during speech rendering of a document, or during the display of + a video using WebVTT to render subtitles.

+

CSS does not define this timeline; + the host language must do so. + If there is no timeline defined for an element, + these pseudo-classes must not match the element.

+

Note: Ancestors of a :current element are also :current, + but ancestors of a :past or :future element are not necessarily :past or :future as well. + A given element matches at most one of :current, :past, or :future.

+

10.1. The Current-element Pseudo-class: :current

+

The :current pseudo-class represents the + element, or an ancestor of the element, that is currently being displayed.

+

Its alternate form :current(), like :matches(), + takes a list of compound selectors as its argument: it represents the :current element that matches the argument or, if that does + not match, the innermost ancestor of the :current element + that does. (If neither the :current element nor its ancestors + match the argument, then the selector does not represent anything.)

+
+ For example, the following rule will highlight whichever paragraph + or list item is being read aloud in a speech rendering of the document: +
:current(p, li, dt, dd) {
+  background: yellow;
+}
+
+
+

10.2. The Past-element Pseudo-class: :past

+

The :past pseudo-class represents any element that is + defined to occur entirely prior to a :current element. + For example, the WebVTT spec defines the :past pseudo-class relative to the current playback position of a media element. + If a time-based order of elements is not defined by the document language, + then this represents any element that is a (possibly indirect) previous + sibling of a :current element.

+

10.3. The Future-element Pseudo-class: :future

+

The :future pseudo-class represents any element that is + defined to occur entirely after a :current element. + For example, the WebVTT spec defines the :future pseudo-class relative to the current playback position of a media element. + If a time-based order of elements is not defined by the document language, + then this represents any element that is a (possibly indirect) next + sibling of a :current element.

+

11. Resource State Pseudos

+

The pseudo-classes in this section apply to elements that represent loaded resources, + particularly images/videos, + and allow authors to select them based on some quality of their state.

+

11.1. Video/Audio Play State: the :playing and :paused pseudo-classes

+

The :playing pseudo-class represents an element + representing an audio, video, or similar resource + that is capable of being “played” or “paused”, + when that element is “playing”. + (This includes both when the element is explicitly playing, + and when it’s temporarily stopped for some reason not connected to user intent, + but will automatically resume when that reason is resolved, + such as a “buffering” state.)

+

The :paused pseudo-class represents the same elements, + but instead match when the element is not “playing”. + (This includes both an explicit “paused” state, + and other non-playing states like “loaded, hasn’t been activated yet”, etc.)

+

12. The Input Pseudo-classes

+

The pseudo-classes in this section mostly apply to elements that take user input, + such as HTML’s input element.

+

12.1. Input Control States

+

12.1.1. The :enabled and :disabled Pseudo-classes

+

The :enabled pseudo-class represents + user interface elements that are in an enabled state; + such elements must have a corresponding disabled state.

+

Conversely, the :disabled pseudo-class represents + user interface elements that are in a disabled state; + such elements must have a corresponding enabled state.

+

What constitutes an enabled state, a disabled state, and a user interface + element is host-language-dependent. In a typical document most elements will be + neither :enabled nor :disabled. + For example, [HTML5] defines non-disabled interactive elements to be :enabled, + and any such elements that are explicitly disabled to be :disabled.

+

Note: CSS properties that might affect a user’s ability + to interact with a given user interface element do not affect whether it + matches :enabled or :disabled; e.g., the display and visibility properties have no effect + on the enabled/disabled state of an element.

+

12.1.2. The Mutability Pseudo-classes: :read-only and :read-write

+

An element matches :read-write if it is user-alterable, + as defined by the document language. + Otherwise, it is :read-only.

+

For example, in [HTML5] a non-disabled non-readonly <input> element is :read-write, + as is any element with the contenteditable attribute set to the true state.

+

12.1.3. The Placeholder-shown Pseudo-class: :placeholder-shown

+

Input elements can sometimes show placeholder text + as a hint to the user on what to type in. + See, for example, the placeholder attribute in [HTML5]. + The :placeholder-shown pseudo-class + matches an input element that is showing such placeholder text.

+

12.1.4. The Default-option Pseudo-class: :default

+

The :default pseudo-class applies to the one or more UI elements + that are the default among a set of similar elements. Typically applies to + context menu items, buttons and select lists/menus.

+

One example is the default submit button among a set of buttons. + Another example is the default option from a popup menu. + In a select-many group (such as for pizza toppings), multiple elements can match :default. + For example, [HTML5] defines that :default matches the “default button” in a form, + the initially-selected <option>(s) in a <select>, + and a few other elements.

+

12.2. Input Value States

+

12.2.1. The Selected-option Pseudo-class: :checked

+

Radio and checkbox elements can be toggled by the user. + Some menu items are “checked” when the user selects them. + When such elements are toggled “on” + the :checked pseudo-class applies. + For example, [HTML5] defines that checked checkboxes, radio buttons, and selected <option> elements match :checked.

+

While the :checked pseudo-class is dynamic in nature, + and can altered by user action, + since it can also be based on the presence of semantic attributes in the document + (such as the selected and checked attributes in [HTML5]), + it applies to all media.

+
+ An unchecked checkbox can be selected by using the negation + pseudo-class: +
input[type=checkbox]:not(:checked)
+
+

12.2.2. The Indeterminate-value Pseudo-class: :indeterminate

+

The :indeterminate pseudo-class applies to UI elements whose + value is in an indeterminate state. + For example, radio and checkbox elements can be toggled between checked and unchecked states, + but are sometimes in an indeterminate state, neither checked nor unchecked. + Similarly a progress meter can be in an indeterminate state when the percent completion is unknown. + For example, [HTML5] defines how checkboxes can be made to match :indeterminate.

+

Like the :checked pseudo-class, :indeterminate applies to all media. Components of a radio-group initialized with no + pre-selected choice, for example, would be :indeterminate even in a static display.

+

12.3. Input Value-checking

+

12.3.1. The Validity Pseudo-classes: :valid and :invalid

+

An element is :valid or :invalid when its contents or value is, respectively, + valid or invalid with respect to data validity semantics defined by the document language + (e.g. [XFORMS11] or [HTML5]). + An element which lacks data validity semantics is neither :valid nor :invalid.

+

Note: There is a difference between an element which has no constraints, + and thus would always be :valid, + and one which has no data validity semantics at all, + and thus is neither :valid nor :invalid. + In HTML, for example, an <input type="text"> element may have no constraints, + but a p element has no validity semantics at all, + and so it never matches either of these pseudo-classes.

+

12.3.2. The Range Pseudo-classes: :in-range and :out-of-range

+

The :in-range and :out-of-range pseudo-classes + apply only to elements that have range limitations. An element is :in-range or :out-of-range when the value + that the element is bound to is in range or out of range with respect + to its range limits as defined by the document language. An element + that lacks data range limits or is not a form control is neither :in-range nor :out-of-range. + E.g. a slider element with a value of 11 presented as a slider control + that only represents the values from 1-10 is :out-of-range. Another + example is a menu element with a value of "E" that happens to be + presented in a popup menu that only has choices "A", "B" and "C".

+

12.3.3. The Optionality Pseudo-classes: :required and :optional

+

A form element is :required or :optional if a value for it is, respectively, required or optional before the + form it belongs to can be validly submitted. Elements that are not + form elements are neither required nor optional.

+

12.3.4. The User-interaction Pseudo-class: :user-invalid

+

The :user-invalid pseudo-class + represents an element with incorrect input, but only after the user has significantly interacted with it. + The :user-invalid pseudo-class + must match an :invalid, :out-of-range, or blank-but-:required elements + between the time the user has attempted to submit the form + and before the user has interacted again with the form element. + User-agents may allow it to match such elements at other times, + as would be appropriate for highlighting an error to the user. + For example, a UA may choose to have :user-invalid match + an :invalid element once the user has typed some text into it + and changed the focus to another element, + and to stop matching only after the user has successfully corrected the input.

+
+ For example, the input in the following document fragment + would match :invalid as soon as the page is loaded + (because it the initial value violates the max-constraint), + but it won’t match :user-invalid until the user significantly interacts with the element, + or attempts to submit the form it’s part of. +
<form>
+  <label>
+    Volume:
+    <input name='vol' type=number min=0 max=10 value=11>
+  </label>
+  ...
+</form>
+
+
+

Cross-check with :-moz-ui-invalid.

+

Add :-moz-ui-valid as :user-valid per WG resolution.

+

Evaluate proposed :dirty pseudo-class

+

Clarify that this (and :invalid/:valid) can apply to form and fieldset elements.

+

13. Tree-Structural pseudo-classes

+

Selectors introduces the concept of structural pseudo-classes to permit selection based on extra information that lies in + the document tree but cannot be represented by other simple selectors or + combinators.

+

Standalone text and other non-element + nodes are not counted when calculating the position of an element in the list + of children of its parent. When calculating the position of an element in + the list of children of its parent, the index numbering starts at 1.

+

The structural pseudo-classes only apply to elements in the document tree; + they must never match pseudo-elements.

+

13.1. :root pseudo-class

+

The :root pseudo-class represents an element that is + the root of the document.

+

For example, in a DOM document, + the :root pseudo-class matches the root element of the Document object. + In HTML, this would be the html element + (unless scripting has been used to modify the document).

+

13.2. :empty pseudo-class

+

The :empty pseudo-class represents an element that has no children at all. + In terms of the document tree, + only element nodes and content nodes + (such as [DOM] text nodes, and entity references) + whose data has a non-zero length must be considered as affecting emptiness; + comments, processing instructions, and other nodes + must not affect whether an element is considered empty or not.

+
+ Examples: p:empty is a valid representation of the following fragment: +
<p></p>
+

foo:empty is not a valid representation for the + following fragments:

+
<foo>bar</foo>
+
<foo><bar>bla</bar></foo>
+
<foo>this is not <bar>:empty</bar></foo>
+
+

The WG is considering whether to allow elements containing only white space to match this selector. + The advantage would be that—as white space is largely collapsible +in HTML and is therefore used for source code formatting, and especially + because elements with omitted end tags are likely to absorb such white +space into their DOM text contents—many elements which authors +perceive of as empty would be selected by this selector, as they expect. + The disadvantages are a potential conflict with Web-compat if there +exist pages that depend on this selector excluding white space; + and that one might consider uncollapsed white space to be significant +content, but the selector cannot change its behavior based on the white-space property. + See discussion.

+

13.3. :blank pseudo-class

+

The :blank pseudo-class is like the :empty pseudo-class, + except that it additionally matches elements that only contain code points affected by whitespace processing. [CSS3TEXT]

+
+ For example, the following element matches :blank, + but not :empty, + because it contains at least one linebreak, and possibly other whitespace: +
<p>    
</p>
+
+

The WG is considering whether to rename this or file its definition under the existing :empty pseudo-class. + See discussion. + There’s also a related issue on a selector for empty input fields which might legitimately steal this name.

+

13.4. Child-indexed Pseudo-classes

+

The pseudo-classes defined in this section select elements + based on their index amongst their inclusive siblings.

+

Note: Selectors 3 described these selectors as selecting elements based on their index in the child list of their parents. + (This description survives in the name of this very section, and the names of several of the pseudo-classes.) + As there was no reason to exclude them from matching elements without parents, + or with non-element parents, + they have been rephrased to refer to an element’s relative index amongst its siblings.

+

13.4.1. :nth-child() pseudo-class

+

The :nth-child(An+B [of S]? ) pseudo-class notation represents elements that + are among An+Bth elements + from the list composed of + their inclusive siblings that match the selector list S. + If S is omitted, + it defaults to *|*.

+

The An+B notation and its interpretation + are defined in CSS Syntax 3 §6 The An+B microsyntax; + it represents any index i = An + B for any positive integer n.

+

For example, this selector could address every other row in a table, + and could be used to alternate the color of paragraph text in a cycle of four.

+
+ Examples: +
:nth-child(even)   /* represents the 2nd, 4th, 6th, etc elements
+:nth-child(10n-1)  /* represents the 9th, 19th, 29th, etc elements */
+:nth-child(10n+9)  /* Same */
+:nth-child(10n+-1) /* Syntactically invalid, and would be ignored */
+
+
+

Note: The specificity of the :nth-child() pseudo-class is + the specificity of a single pseudo-class plus + the specificity of its selector argument S, if any. + See §16 Calculating a selector’s specificity. + Thus S:nth-child(An+B) and :nth-child(An+B of S) have the exact same specificity, + although they do differ in behavior + (see example below).

+
+ By passing a selector argument, + we can select the Nth element that matches that selector. + For example, the following selector matches the first three “important” list items, + denoted by the .important class: +
:nth-child(-n+3 of li.important)
+

Note that this is different from moving the selector outside of the function, like:

+
li.important:nth-child(-n+3)
+

This selector instead just selects the first three children + if they also happen to be "important" list items.

+
+
+ Here’s another example of using the selector argument, + to ensure that zebra-striping a table works correctly. +

Normally, to zebra-stripe a table’s rows, + an author would use CSS similar to the following:

+
tr {
+  background: white;
+}
+tr:nth-child(even) {
+  background: silver;
+}
+
+

However, if some of the rows are hidden and not displayed, + this can break up the pattern, + causing multiple adjacent rows to have the same background color. + Assuming that rows are hidden with the [hidden] attribute in HTML, + the following CSS would zebra-stripe the table rows robustly, + maintaining a proper alternating background + regardless of which rows are hidden:

+
tr {
+  background: white;
+}
+tr:nth-child(even of :not([hidden])) {
+  background: silver;
+}
+
+
+

13.4.2. :nth-last-child() pseudo-class

+

The :nth-last-child(An+B [of S]? ) pseudo-class notation represents elements that + are among An+Bth elements + from the list composed of + their inclusive siblings that match the selector list S, + counting backwards from the end. + If S is omitted, + it defaults to *|*.

+

Note: The specificity of the :nth-last-child() pseudo-class, + like the :nth-child() pseudo-class, + combines the specificity of a regular pseudo-class + with that of its selector argument S. + See §16 Calculating a selector’s specificity.

+

The CSS Syntax Module [CSS3SYN] defines the An+B notation.

+
+ Examples: +
tr:nth-last-child(-n+2)    /* represents the two last rows of an HTML table */
+
+foo:nth-last-child(odd)    /* represents all odd foo elements in their parent element,
+                              counting from the last one */
+
+
+

13.4.3. :first-child pseudo-class

+

The :first-child pseudo-class + represents an element that if first among its inclusive siblings. + Same as :nth-child(1).

+
+ Examples: + The following selector represents a p element that is + the first child of a div element: +
div > p:first-child
+

This selector can represent the p inside the div of the following fragment:

+
<p> The last P before the note.</p>
+<div class="note">
+   <p> The first P inside the note.</p>
+</div>
+
+

but cannot represent the second p in the following fragment:

+
<p> The last P before the note.</p>
+<div class="note">
+   <h2> Note </h2>
+   <p> The first P inside the note.</p>
+</div>
+
+

The following two selectors are usually equivalent:

+
* > a:first-child /* a is first child of any element */
+a:first-child /* Same (assuming a is not the root element) */
+
+
+

13.4.4. :last-child pseudo-class

+

The :last-child pseudo-class + represents an element that is last among its inclusive siblings. + Same as :nth-last-child(1).

+
+ Example: + The following selector represents a list item li that + is the last child of an ordered list ol. +
ol > li:last-child
+
+

13.4.5. :only-child pseudo-class

+

The :only-child pseudo-class + represents an element that has no siblings. + Same as :first-child:last-child or :nth-child(1):nth-last-child(1), + but with a lower specificity.

+

13.5. Typed Child-indexed Pseudo-classes

+

The pseudo-elements in this section are similar to the Child Index Pseudo-classes, + but they resolve based on an element’s index among elements of the same type (tag name) in their sibling list.

+

13.5.1. :nth-of-type() pseudo-class

+

The :nth-of-type(An+B) pseudo-class notation + represents the same elements that would be matched by :nth-child(|An+B| of S), + where S is a type selector and namespace prefix matching the element in question. + For example, + when considering whether an HTML img element matches this pseudo-class, + the S in question is html|img (assuming an appropriate html namespace is declared).

+
+ CSS example: + This allows an author to alternate the position of floated images: +
img:nth-of-type(2n+1) { float: right; }
+img:nth-of-type(2n) { float: left; }
+
+
+

Note: If the type of the element is known ahead of time, + this pseudo-class is equivalent to using :nth-child() with a type selector. + That is, img:nth-of-type(2) is equivalent to *:nth-child(2 of img).

+

13.5.2. :nth-last-of-type() pseudo-class

+

The :nth-last-of-type(An+B) pseudo-class notation + represents the same elements that would be matched by :nth-last-child(|An+B| of S), + where S is a type selector and namespace prefix matching the element in question. + For example, + when considering whether an HTML img element matches this pseudo-class, + the S in question is html|img (assuming an appropriate html namespace is declared).

+
+ Example: + To represent all h2 children of an XHTML body except the first and last, one could use the + following selector: +
body > h2:nth-of-type(n+2):nth-last-of-type(n+2) 
+

In this case, one could also use :not(), although the + selector ends up being just as long:

+
body > h2:not(:first-of-type):not(:last-of-type) 
+
+

13.5.3. :first-of-type pseudo-class

+

The :first-of-type pseudo-class + represents the same element as :nth-of-type(1).

+
+ Example: + The following selector represents a definition title dt inside a definition list dl, this dt being the first of its type in the list of children of + its parent element. +
dl dt:first-of-type
+

It is a valid description for the first two dt elements in the following example but not for the third one:

+
<dl>
+  <dt>gigogne</dt>
+  <dd>
+    <dl>
+      <dt>fusée</dt>
+      <dd>multistage rocket</dd>
+      <dt>table</dt>
+      <dd>nest of tables</dd>
+    </dl>
+  </dd>
+</dl>
+
+
+

13.5.4. :last-of-type pseudo-class

+

The :last-of-type pseudo-class + represents the same element as :nth-last-of-type(1).

+
+ Example: + The following selector represents the last data cell td of a table row tr. +
tr > td:last-of-type
+
+

13.5.5. :only-of-type pseudo-class

+

The :only-of-type pseudo-class + represents the same element as :first-of-type:last-of-type.

+

14. Combinators

+

14.1. Descendant combinator ( )

+

At times, authors may want selectors to describe an element that is + the descendant of another element in the document tree (e.g., "an em element that is contained within an H1 element"). + The descendant combinator expresses such a relationship.

+

A descendant combinator is whitespace that separates two compound selectors.

+

A selector of the form A B represents an element B that is an + arbitrary descendant of some ancestor element A.

+
+ Examples: + For example, consider the following selector: +
h1 em
+

It represents an em element being the descendant of + an h1 element. It is a correct and valid, but partial, + description of the following fragment:

+
<h1>This <span class="myclass">headline
+is <em>very</em> important</span></h1>
+
+

The following selector:

+
div * p
+

represents a p element that is a grandchild or later + descendant of a div element. Note the whitespace on + either side of the "*" is not part of the universal selector; the + whitespace is a combinator indicating that the div must be the + ancestor of some element, and that that element must be an ancestor + of the p. + The following selector, which combines descendant combinators and attribute selectors, represents an + element that (1) has the href attribute set and (2) is + inside a p that is itself inside a div:

+
div p *[href]
+
+

14.2. Child combinator (>)

+

A child combinator describes a childhood relationship + between two elements. A child combinator is made of the + "greater-than sign" (U+003E, >) code point and + separates two compound selectors.

+
+ Examples: + The following selector represents a p element that is + child of body: +
body > p
+

The following example combines descendant combinators and child + combinators.

+
div ol>li p
+

It represents a p element that is a descendant of an li element; the li element must be the + child of an ol element; the ol element must + be a descendant of a div. Notice that the optional white + space around the ">" combinator has been left out.

+
+

For information on selecting the first child of an element, + please see the section on the :first-child pseudo-class above.

+

14.3. Next-sibling combinator (+)

+

The next-sibling combinator is made of the “plus sign” + (U+002B, +) code point that separates two compound selectors. + The elements represented by the two compound selectors share the same parent in the document tree + and the element represented by the first compound selector immediately precedes the element represented by the second one. + Non-element nodes (e.g. text between elements) + are ignored when considering the adjacency of elements.

+
+ Examples: + The following selector represents a p element + immediately following a math element: +
math + p
+

The following selector is conceptually similar to the one in the + previous example, except that it adds an attribute selector — it + adds a constraint to the h1 element, that it must have class="opener":

+
h1.opener + h2
+
+

14.4. Subsequent-sibling combinator (~)

+

The subsequent-sibling combinator is made of the "tilde" + (U+007E, ~) code point that separates two compound selectors. + The elements represented by the two compound selectors share + the same parent in the document tree and the element represented by + the first compound selector precedes (not necessarily immediately) the element + represented by the second one.

+
+ +
h1 ~ pre
+

represents a pre element following an h1. It + is a correct and valid, but partial, description of:

+
<h1>Definition of the function a</h1>
+<p>Function a(x) has to be applied to all figures in the table.</p>
+<pre>function a(x) = 12x/13.5</pre>
+
+
+

15. Grid-Structural Selectors

+

The double-association of a cell in a 2D grid (to its row and column) + cannot be represented by parentage in a hierarchical markup language. + Only one of those associations can be represented hierarchically: the + other must be explicitly or implicitly defined in the document language + semantics. In both HTML and DocBook, two of the most common hierarchical + markup languages, the markup is row-primary (that is, the row associations + are represented hierarchically); the columns must be implied. + To be able to represent such implied column-based relationships, the column combinator and the :nth-col() and :nth-last-col() pseudo-classes + are defined. + In a column-primary format, these pseudo-classes match against row associations instead.

+

15.1. Column combinator

+

The column combinator, which consists of two pipes (||) + represents the relationship of a column element + to a cell element belonging to the column it represents. + Column membership is determined based on the semantics of the document language only: + whether and how the elements are presented is not considered. + If a cell element belongs to more than one column, + it is represented by a selector indicating membership in any of those columns.

+
+ The following example makes cells C, E, and G gray. +
col.selected || td {
+  background: gray;
+  color: white;
+  font-weight: bold;
+}
+
+
<table>
+  <col span="2">
+  <col class="selected">
+  <tr><td>A <td>B <td>C
+  <tr><td colspan="2">D <td>E
+  <tr><td>F <td colspan="2">G
+</table>
+
+
+

15.2. :nth-col() pseudo-class

+

The :nth-col(An+B) pseudo-class notation represents a cell element belonging to a column + that has An+B-1 columns before it, for any positive + integer or zero value of n. Column membership is determined + based on the semantics of the document language only: whether and how the + elements are presented is not considered. If a cell element belongs to + more than one column, it is represented by a selector indicating any of + those columns.

+

The CSS Syntax Module [CSS3SYN] defines the An+B notation.

+

15.3. :nth-last-col() pseudo-class

+

The :nth-last-col(An+B) pseudo-class notation represents a cell element belonging to a column + that has An+B-1 columns after it, for any positive + integer or zero value of n. Column membership is determined + based on the semantics of the document language only: whether and how the + elements are presented is not considered. If a cell element belongs to + more than one column, it is represented by a selector indicating any of + those columns.

+

The CSS Syntax Module [CSS3SYN] defines the An+B notation.

+

16. Calculating a selector’s specificity

+

A selector’s specificity is calculated for a given element as follows:

+
    +
  • count the number of ID selectors in the selector (= A) +
  • count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= B) +
  • count the number of type selectors and pseudo-elements in the selector (= C) +
  • ignore the universal selector +
+

If the selector is a selector list, + this number is calculated for each selector in the list. + For a given matching process against the list, the specificity in effect + is that of the most specific selector in the list that matches.

+

A few pseudo-classes provide “evaluation contexts” for other selectors, + and so have their specificity defined by their contents and how they match:

+

See also issue 1027.

+
    +
  • The specificity of a :matches() or :has() pseudo-class is replaced by + the specificity applicable to its selector list argument. + (When :matches() contains only compound selectors, + the full selector’s specificity is thus equivalent to + expanding out all the combinations in full, without :matches(); + fully generalized, the specificity of :matches() is + the specificity of the most specific selector within it that matches. + The behavior for comma-separated arguments to :has() is analogous.) +
  • Analogously, the specificity of an :nth-child() or :nth-last-child() selector + is the specificity of the pseudo class itself (counting as one pseudo-class selector) + plus the specificity of its selector list argument (if any). +
  • The specificity of a :not() pseudo-class is replaced by + the specificity of the most specific complex selector in its selector list argument. +
  • The specificity of a :something() pseudo-class is replaced by zero. +
+
+ For example: +
    +
  • :matches(em, #foo) has + a specificity of (0,0,1)--like a tag selector--when matched against <em>, + and a specificity of (1,0,0)--like an ID selector--when matched against <em id=foo>. +
  • div:something(em, #foo#bar#baz) has + a specificity of (0,0,1): only the div contributes to selector specificity. +
  • :nth-child(even of li, .item) has + a specificity of (0,1,1)--like a tag selector plus a pseudo-class--when matched against <li>, + and a specificity of (0,2,0)--like a class selector plus a pseudo-class--when matched against <li class=item id=foo>. +
  • :not(em, #foo) has + a specificity of (1,0,0)--like an ID selector--whenever it matches any element. +
+
+

Specificities are compared by comparing the three components in order: + the specificity with a larger A value is more specific; + if the two A values are tied, + then the specificity with a larger B value is more specific; + if the two B values are also tied, + then the specificity with a larger C value is more specific; + if all the values are tied, + the two specificities are equal.

+

Due to storage limitations, + implementations may have limitations on the size of A, B, or C. + If so, values higher than the limit must be clamped to that limit, + and not overflow.

+
+ Examples: +
*               /* a=0 b=0 c=0 */
+LI              /* a=0 b=0 c=1 */
+UL LI           /* a=0 b=0 c=2 */
+UL OL+LI        /* a=0 b=0 c=3 */
+H1 + *[REL=up]  /* a=0 b=1 c=1 */
+UL OL LI.red    /* a=0 b=1 c=3 */
+LI.red.level    /* a=0 b=2 c=1 */
+#x34y           /* a=1 b=0 c=0 */
+#s12:not(FOO)   /* a=1 b=0 c=1 */
+.foo :matches(.bar, #baz)
+                /* Either a=1 b=1 c=0
+                   or a=0 b=2 c=0, depending
+                   on the element being matched. */
+
+
+

Note: Repeated occurrences of the + same simple selector are allowed and do increase specificity.

+

Note: The specificity of the styles + specified in an HTML style attribute is described in CSS Style Attributes. [CSSSTYLEATTR]

+

17. Grammar

+

Selectors are parsed according to the following grammar:

+
<selector-list> = <complex-selector-list>
+
+<complex-selector-list> = <complex-selector>#
+
+<compound-selector-list> = <compound-selector>#
+
+<simple-selector-list> = <simple-selector>#
+
+<relative-selector-list> = <relative-selector>#
+
+
+<complex-selector> = <compound-selector> [ <combinator>? <compound-selector> ]*
+
+<relative-selector> = <combinator>? <complex-selector>
+
+<compound-selector> = [ <type-selector>? <subclass-selector>*
+                        [ <pseudo-element-selector> <pseudo-class-selector>* ]* ]!
+
+<simple-selector> = <type-selector> | <subclass-selector>
+
+
+<combinator> = '>' | '+' | '~' | [ '||' ]
+
+<type-selector> = <wq-name> | <ns-prefix>? '*'
+
+<ns-prefix> = [ <ident-token> | '*' ]? '|'
+
+<wq-name> = <ns-prefix>? <ident-token>
+
+<subclass-selector> = <id-selector> | <class-selector> |
+                      <attribute-selector> | <pseudo-class-selector>
+
+<id-selector> = <hash-token>
+
+<class-selector> = '.' <ident-token>
+
+<attribute-selector> = '[' <wq-name> ']' |
+                       '[' <wq-name> <attr-matcher> [ <string-token> | <ident-token> ] <attr-modifier>? ']'
+
+<attr-matcher> = [ '~' | '|' | '^' | '$' | '*' ]? '='
+
+<attr-modifier> = i
+
+<pseudo-class-selector> = ':' <ident-token> |
+                          ':' <function-token> <any-value> ')'
+
+<pseudo-element-selector> = ':' <pseudo-class-selector>
+
+

In interpreting the above grammar, + the following rules apply:

+ +

Note: A selector is also subject to a variety of more specific syntactic constraints, + and adherence to the grammar above is necessary but not sufficient for the selector to be considered valid. + See §3.9 Invalid Selectors and Error Handling for additional rules for parsing selectors.

+

Note: The grammar above states that a combinator is optional + between two <compound-selector>s in a <complex-selector>. + This is only for grammatical purposes, + as the CSS Value Definition Syntax’s lax treatment of whitespace + makes it difficult to indicate that a grammar term can be whitespace. + "Omitting" a combinator is actually just specifying the descendant combinator.

+

Note: In general, + a <pseudo-element-selector> is only valid + if placed at the end of the last <compound-selector> in a <complex-selector>. + In some circumstances, however, + it can be followed by more <pseudo-element-selector>s or <pseudo-class-selector>s; + but these are specified on a case-by-case basis. + (For example, the user action pseudo-classes are allowed after any pseudo-element, + and the tree-abiding pseudo-elements are allowed after the ::slotted() pseudo-element)

+

18. API Hooks

+

To aid in the writing of specs that use Selectors concepts, + this section defines several API hooks that can be invoked by other specifications.

+

Are these still necessary now that we have more rigorous definitions for match and invalid selector? + Nouns are a lot easier to coordinate across specification than predicates, + and details like the exact order of elements returned from querySelector seem to make more sense being defined in the DOM specification than in Selectors.

+

18.1. Parse A Selector

+

This section defines how to parse a selector from a string source. + It returns either a complex selector list, + or failure.

+
    +
  1. Let selector be the result of parsing source as a <selector-list>. + If it does not match the grammar, + return failure. +
  2. Otherwise, + if any simple selectors in selector are not recognized by the user agent, + or selector is otherwise invalid in some way + (such as, for example, containing an undeclared namespace prefix), + return failure. +
  3. Otherwise, + return selector. +
+

18.2. Parse A Relative Selector

+

This section defines how to parse a relative selector from a string source, + against :scope elements refs. + It returns either a complex selector list, + or failure.

+
    +
  1. Let selector be the result of parsing source as a <relative-selector-list>. + If it does not match the grammar, + return failure. +
  2. Otherwise, + if any simple selectors in selector are not recognized by the user agent, + or selector is otherwise invalid in some way + (such as, for example, containing an undeclared namespace prefix), + return failure. +
  3. Otherwise, absolutize selector with refs as the :scope elements. +
  4. Return selector. +
+

18.3. Match a Selector Against an Element

+

This section defines how to match a selector against an element.

+

APIs using this algorithm must provide a selector and an element.

+

Callers may optionally provide:

+
    +
  • + a set of :scope elements, + for resolving the :scope pseudo-class against. + If not specified, + the set defaults to being empty. +

    Should it instead default to the root element, + to match the definition of :scope?

    +

    If the selector is a relative selector, + the set of :scope elements must not be empty.

    +
+

This algorithm returns either success or failure.

+

For each complex selector in the given selector (which is taken to be a list of complex selectors), + match the complex selector against element, + as described in the following paragraph. + If the matching returns success for any complex selector, + then the algorithm return success; otherwise it returns failure.

+

To match a complex selector against an element, + process it compound selector at a time, + in right-to-left order. + This process is defined recursively as follows:

+
    +
  • If any simple selectors in the rightmost compound selector + does not match the element, return failure. +
  • Otherwise, if there is only one compound selector in the + complex selector, return success. +
  • Otherwise, consider all possible elements + that could be related to this element by the rightmost combinator. + If the operation of matching the selector consisting of this selector + with the rightmost compound selector and rightmost combinator removed + against any one of these elements returns success, then return success. + Otherwise, return failure. +
+

18.4. Match a Selector Against a Pseudo-element

+

This section defines how to match a selector against a pseudo-element.

+

APIs using this algorithm must provide a selector and a pseudo-element. + They may optionally provide the same things they may optionally provide + to the algorithm to match a selector against an element.

+

This algorithm returns success or failure.

+

For each complex selector in the given selector, if both:

+
    +
  • the rightmost simple selector in the complex selector + matches pseudo-element, and +
  • the result of running match a complex selector against an element on the remainder of the complex selector (with just the rightmost simple selector + of its rightmost complex selector removed), pseudo-element’s corresponding element, + and any optional parameters provided to this algorithm + returns success, +
+ then return success. +

Otherwise + (that is, if this doesn’t happen for any of the complex selectors in selector), + return failure.

+

18.5. Match a Selector Against a Tree

+

This section defines how to match a selector against a tree.

+

APIs using this algorithm must provide a selector, + and one or more root elements indicating the trees that will be searched by the selector. + All of the root elements must share the same root, + or else calling this algorithm is invalid.

+

They may optionally provide:

+
    +
  • + A scoping root indicating the selector is scoped. + If not specified, + the selector defaults to being unscoped. +

    This is now redundant with the root elements.

    +
  • + A set of :scope elements, + which will match the :scope pseudo-class. + If not specified, + then if the selector is a scoped selector, + the set of :scope elements default to the scoping root; + otherwise, + it defaults to the root elements. +

    Note: Note that if the selector is scoped, + the scoping root is automatically taken as the :scope element, + so it doesn’t have to be provided explicitly + unless a different result is desired.

    +
  • + Which pseudo-elements are allowed to show up in the match list. + If not specified, this defaults to allowing all pseudo-elements. +

    Only the ::before and ::after pseudo-elements are really + handled in any way remotely like this.

    +
+

This algorithm returns a (possibly empty) list of elements.

+
    +
  1. Start with a list of candidate elements, + which are the the root elements and all of their descendant elements, + sorted in shadow-including tree order, + unless otherwise specified. +
  2. If an optional scoping root was provided, + then remove from the candidate elements any elements that are not descendants of the scoping root. +
  3. Initialize the selector match list to empty. +
  4. + For each element in the set of candidate elements: +
      +
    1. If the result of match a selector against an element for element and selector is success, + add element to the selector match list. +
    2. + For each possible pseudo-element associated with element that is one of the pseudo-elements allowed to show up in the match list, + if the result of match a selector against a pseudo-element for the pseudo-element and selector is success, + add the pseudo-element to the selector match list. +

      The relative position of pseudo-elements + in selector match list is undefined. + There’s not yet a context that exposes this information, + but we need to decide on something eventually, + before something is exposed.

      +
    +
+

19. Appendix A: Guidance on Mapping Source Documents & Data to an Element Tree

+

This section is informative.

+

The element tree structure described by the DOM is powerful and useful, + but generic enough to model pretty much any language that describes tree-based data + (or even graph-based, with a suitable interpretation).

+

Some languages, like HTML, already have well-defined procedures + for producing a DOM object from a resource. + If a given language does not, + such a procedure must be defined + in order for Selectors to apply to documents in that language.

+

At minimum, + the document language must define what maps to the DOM concept of an "element".

+

The primary one-to-many relationship between nodes—parent/child in tree-based structures, + element/neighbors in graph-based structures—should be reflected as the child nodes of an element.

+

Other features of the element should be mapped + to something that serves a similar purpose to the same feature in DOM:

+
+
type +
+ If the elements in the document language have some notion of "type" + as a basic distinguisher between different groups of elements, + it should be reflected as the "type" feature. +

If this "type" can be separated into a "basic" name + and a "namespace" that groups names into higher-level groups, + the latter should be reflected as the "namespace" feature. + Otherwise, the element shouldn’t have a "namespace" feature, + and the entire name should be reflected as the "type" feature.

+
id +
+ If some aspect of the element functions as a unique identifier across the document, + it should be mapped to the "id" feature. +

Note: While HTML only allows an element to have a single ID, + this should not be taken as a general restriction. + The important quality of an ID is that each ID should be associated with a single element; + a single element can validly have multiple IDs.

+
classes and attributes +
Aspects of the element that are useful for identifying the element, + but are not generally unique to elements within a document, + should be mapped to the "class" or "attribute" features + depending on if they’re something equivalent to a "label" (a string by itself) + or a "property" (a name/value pair) +
pseudo-classes and pseudo-attributes +
+ If any elements match any pseudo-classes or have any pseudo-elements, + that must be explicitly defined. +

Some pseudo-classes are *syntactical*, + like :has() and :matches(), + and thus should always work. + Need to indicate that somewhere. + Probably the structural pseudos always work + whenever the child list is ordered.

+
+
+ For example, JSONSelect is a library that uses selectors + to extract information from JSON documents. +
    +
  • The "elements" of the JSON document + are each array, object, boolean, string, number, or null. + The array and object elements have their contents as children. +
  • Each element’s type is its JS type name: + "array", "object", etc. +
  • Children of an object + have their key as a class. +
  • Children of an array match the :first-child, :nth-child(), etc pseudo-classes. +
  • The root object matches :root. +
  • It additionally defines :val() and :contains() pseudo-classes, + for matching boolean/number/string elements with a particular value + or which contain a particular substring. +
+

This structure is sufficient to allow powerful, compact querying of JSON documents with selectors.

+
+

20. Changes

+

Significant changes since the 2 May 2013 Working Draft include:

+
    +
  • Added the :target-within, :focus-within, :focus-visible, :playing, and :paused pseudo-classes. +
  • Added a zero-specificity :matches()-type pseudo-class, with name TBD. +
  • Replaced subject indicator (!) feature with :has(). +
  • Replaced the :nth-match() and :nth-last-match() selectors + with :nth-child(… of selector) and :nth-last-child(… of selector). +
  • Changed the :active-drop-target, :valid-drop-target, :invalid-drop-target with :drop(). +
  • Sketched out an empty-or-whitespace-only selector for discussion (:blank). + (See open issue.) +
  • Renamed :user-error to :user-invalid. + (See Discussion) +
  • Renamed :nth-column()/:nth-last-column() to :nth-col()/:nth-last-col() to avoid naming confusion with a potential ::column pseudo-class. +
  • Changed the non-functional form of the :local-link pseudo-class to account for fragment URLs. +
  • Removed the functional form of the :local-link() pseudo-class and reference combinator for lack of interest. +
  • Rewrote selectors grammar using the CSS Value Definition Syntax. +
  • Split out relative selectors from scoped selectors, + as these are different concepts that can be independently invoked. +
  • + Moved definition of <An+B> microsyntax to CSS Syntax. +

    Semantic definition should probably move back here.

    +
  • + Added new sections: +
      +
    • + §3.2 Data Model +

      Need to define tree for XML.

      +
    • + §18 API Hooks +
        +
      • Note that earlier versions of this section defined a section on evaluating a selector, + but that section is no longer present. + Specifications referencing that section should instead reference + the algorithm to match a selector against a tree. +
      +
    +
  • Removed restriction on combinators within :matches() and :not(); + see discussion. +
  • Defined specificity of a selector list. (Why?) +
  • Required quotes around :lang() values involving an asterisk; + only language codes which happen to bhe CSS identifiers can be used unquoted. +
+

Note: The 1 February 2018 draft included an inadvertent commit of unfinished work; + 2 February 2018 has reverted this commit (and fixed some links because why not).

+

21. Acknowledgements

+

The CSS working group would like to thank everyone who contributed + to the previous Selectors specifications over the years, + as those specifications formed the basis for this one. + In particular, the working group would like to extend special thanks + to the following for their specific contributions to Selectors Level 4: + L. David Baron, + Andrew Fedoniouk, + Ian Hickson, + Grey Hodge, + Lachlan Hunt, + Jason Cranford Teague

+

22. Privacy and Security Considerations

+

This specification introduces no new privacy or security considerations, +as selectors do not provide any ability not already possible by walking the DOM manually.

+
+

Conformance

+

Document conventions

+

Conformance requirements are expressed with a combination of + descriptive assertions and RFC 2119 terminology. The key words “MUST”, + “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, + “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this + document are to be interpreted as described in RFC 2119. + However, for readability, these words do not appear in all uppercase + letters in this specification.

+

All of the text of this specification is normative except sections + explicitly marked as non-normative, examples, and notes. [RFC2119]

+

Examples in this specification are introduced with the words “for example” + or are set apart from the normative text with class="example", + like this:

+
+ +

This is an example of an informative example.

+
+

Informative notes begin with the word “Note” and are set apart from the + normative text with class="note", like this:

+

Note, this is an informative note.

+

Advisements are normative sections styled to evoke special attention and are + set apart from other normative text with <strong class="advisement">, like + this: UAs MUST provide an accessible alternative.

+

Conformance classes

+

Conformance to this specification + is defined for three conformance classes:

+
+
style sheet +
A CSS + style sheet. +
renderer +
A UA that interprets the semantics of a style sheet and renders + documents that use them. +
authoring tool +
A UA that writes a style sheet. +
+

A style sheet is conformant to this specification + if all of its statements that use syntax defined in this module are valid + according to the generic CSS grammar and the individual grammars of each + feature defined in this module.

+

A renderer is conformant to this specification + if, in addition to interpreting the style sheet as defined by the + appropriate specifications, it supports all the features defined + by this specification by parsing them correctly + and rendering the document accordingly. However, the inability of a + UA to correctly render a document due to limitations of the device + does not make the UA non-conformant. (For example, a UA is not + required to render color on a monochrome monitor.)

+

An authoring tool is conformant to this specification + if it writes style sheets that are syntactically correct according to the + generic CSS grammar and the individual grammars of each feature in + this module, and meet all other conformance requirements of style sheets + as described in this module.

+

Requirements for Responsible Implementation of CSS

+

The following sections define several conformance requirements + for implementing CSS responsibly, + in a way that promotes interoperability in the present and future.

+

Partial Implementations

+

So that authors can exploit the forward-compatible parsing rules to assign fallback values, CSS renderers must treat as invalid + (and ignore as appropriate) + any at-rules, properties, property values, keywords, and other syntactic constructs + for which they have no usable level of support. + In particular, user agents must not selectively ignore + unsupported property values and honor supported values in a single multi-value property declaration: + if any value is considered invalid (as unsupported values must be), + CSS requires that the entire declaration be ignored.

+

Implementations of Unstable and Proprietary Features

+

To avoid clashes with future stable CSS features, + the CSSWG recommends following best practices for the implementation of unstable features and proprietary extensions to CSS.

+

Implementations of CR-level Features

+

Once a specification reaches the Candidate Recommendation stage, + implementers should release an unprefixed implementation + of any CR-level feature they can demonstrate + to be correctly implemented according to spec, + and should avoid exposing a prefixed variant of that feature.

+

To establish and maintain the interoperability of CSS across + implementations, the CSS Working Group requests that non-experimental + CSS renderers submit an implementation report (and, if necessary, the + testcases used for that implementation report) to the W3C before + releasing an unprefixed implementation of any CSS features. Testcases + submitted to W3C are subject to review and correction by the CSS + Working Group.

+

+ Further information on submitting testcases and implementation reports + can be found from on the CSS Working Group’s website at https://www.w3.org/Style/CSS/Test/. + Questions should be directed to the public-css-testsuite@w3.org mailing list. + +

+

Index

+

Terms defined by this specification

+ +

Terms defined by reference

+ +

References

+

Normative References

+
+
[CSS-DISPLAY-3] +
Elika Etemad. CSS Display Module Level 3. 20 July 2017. WD. URL: https://www.w3.org/TR/css-display-3/ +
[CSS-PSEUDO-4] +
Daniel Glazman; Elika Etemad; Alan Stearns. CSS Pseudo-Elements Module Level 4. 7 June 2016. WD. URL: https://www.w3.org/TR/css-pseudo-4/ +
[CSS-SCOPING-1] +
Tab Atkins Jr.; Elika Etemad. CSS Scoping Module Level 1. 3 April 2014. WD. URL: https://www.w3.org/TR/css-scoping-1/ +
[CSS-VALUES-3] +
Tab Atkins Jr.; Elika Etemad. CSS Values and Units Module Level 3. 29 September 2016. CR. URL: https://www.w3.org/TR/css-values-3/ +
[CSS-WRITING-MODES-3] +
Elika Etemad; Koji Ishii. CSS Writing Modes Level 3. 15 December 2015. CR. URL: https://www.w3.org/TR/css-writing-modes-3/ +
[CSS21] +
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 7 June 2011. REC. URL: https://www.w3.org/TR/CSS2/ +
[CSS3NAMESPACE] +
Elika Etemad. CSS Namespaces Module Level 3. 20 March 2014. REC. URL: https://www.w3.org/TR/css-namespaces-3/ +
[CSS3SYN] +
Tab Atkins Jr.; Simon Sapin. CSS Syntax Module Level 3. 20 February 2014. CR. URL: https://www.w3.org/TR/css-syntax-3/ +
[CSS3TEXT] +
Elika Etemad; Koji Ishii. CSS Text Module Level 3. 22 August 2017. WD. URL: https://www.w3.org/TR/css-text-3/ +
[DOM] +
Anne van Kesteren. DOM Standard. Living Standard. URL: https://dom.spec.whatwg.org/ +
[HTML] +
Anne van Kesteren; et al. HTML Standard. Living Standard. URL: https://html.spec.whatwg.org/multipage/ +
[INFRA] +
Anne van Kesteren; Domenic Denicola. Infra Standard. Living Standard. URL: https://infra.spec.whatwg.org/ +
[RFC2119] +
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119 +
[SELECT] +
Tantek Çelik; et al. Selectors Level 3. 29 September 2011. REC. URL: https://www.w3.org/TR/css3-selectors/ +
[SVG2] +
Nikos Andronikos; et al. Scalable Vector Graphics (SVG) 2. 15 September 2016. CR. URL: https://www.w3.org/TR/SVG2/ +
[URL] +
Anne van Kesteren. URL Standard. Living Standard. URL: https://url.spec.whatwg.org/ +
+

Informative References

+
+
[BCP47] +
A. Phillips; M. Davis. Tags for Identifying Languages. September 2009. IETF Best Current Practice. URL: https://tools.ietf.org/html/bcp47 +
[CSS22] +
Bert Bos. Cascading Style Sheets Level 2 Revision 2 (CSS 2.2) Specification. 12 April 2016. WD. URL: https://www.w3.org/TR/CSS22/ +
[CSS3UI] +
Tantek Çelik; Florian Rivoal. CSS Basic User Interface Module Level 3 (CSS3 UI). 2 March 2017. CR. URL: https://www.w3.org/TR/css-ui-3/ +
[CSSSTYLEATTR] +
Tantek Çelik; Elika Etemad. CSS Style Attributes. 7 November 2013. REC. URL: https://www.w3.org/TR/css-style-attr/ +
[HTML5] +
Ian Hickson; et al. HTML5. 28 October 2014. REC. URL: https://www.w3.org/TR/html5/ +
[ITS20] +
David Filip; et al. Internationalization Tag Set (ITS) Version 2.0. 29 October 2013. REC. URL: https://www.w3.org/TR/its20/ +
[MATHML] +
Patrick D F Ion; Robert R Miner. Mathematical Markup Language (MathML) 1.01 Specification. 7 July 1999. REC. URL: https://www.w3.org/TR/REC-MathML/ +
[RFC4647] +
A. Phillips; M. Davis. Matching of Language Tags. September 2006. Best Current Practice. URL: https://tools.ietf.org/html/rfc4647 +
[SVG11] +
Erik Dahlström; et al. Scalable Vector Graphics (SVG) 1.1 (Second Edition). 16 August 2011. REC. URL: https://www.w3.org/TR/SVG11/ +
[XFORMS11] +
John Boyer. XForms 1.1. 20 October 2009. REC. URL: https://www.w3.org/TR/xforms11/ +
[XML-NAMES] +
Tim Bray; et al. Namespaces in XML 1.0 (Third Edition). 8 December 2009. REC. URL: https://www.w3.org/TR/xml-names/ +
[XML10] +
Tim Bray; et al. Extensible Markup Language (XML) 1.0 (Fifth Edition). 26 November 2008. REC. URL: https://www.w3.org/TR/xml/ +
+

Issues Index

+
+
The categorization of things into the “live” or snapshot profiles needs implementor review. + If some things currently not in the live profile can reasonably be done in CSS Selectors, + we should move them.
+
Pseudo-elements aren’t handled here, and should be.
+ +
Clarify that :not() and :matches() can be used when containing above-mentioned pseudos.
+
Does ::first-line:not(:focus) match anything?
+
Why this exception for the explicit universal selector?
+
This pseudo-class needs a name. See previous discussion, open issue.
+
Add comma-separated syntax for multiple-value matching? + e.g. [rel ~= next, prev, up, first, last]
+
There’s a desire from authors to propagate :focus from a form control to its associated label element; + the main objection seems to be implementation difficulty. + See CSSWG issue (CSS) and WHATWG issue (HTML).
+
Turn this scenario into an example.
+
Cross-check with :-moz-ui-invalid.
+
Add :-moz-ui-valid as :user-valid per WG resolution.
+
Evaluate proposed :dirty pseudo-class
+
Clarify that this (and :invalid/:valid) can apply to form and fieldset elements.
+
The WG is considering whether to allow elements containing only white space to match this selector. + The advantage would be that—as white space is largely collapsible +in HTML and is therefore used for source code formatting, and especially + because elements with omitted end tags are likely to absorb such white +space into their DOM text contents—many elements which authors +perceive of as empty would be selected by this selector, as they expect. + The disadvantages are a potential conflict with Web-compat if there +exist pages that depend on this selector excluding white space; + and that one might consider uncollapsed white space to be significant +content, but the selector cannot change its behavior based on the white-space property. + See discussion.
+
The WG is considering whether to rename this or file its definition under the existing :empty pseudo-class. + See discussion. + There’s also a related issue on a selector for empty input fields which might legitimately steal this name.
+
See also issue 1027.
+
Are these still necessary now that we have more rigorous definitions for match and invalid selector? + Nouns are a lot easier to coordinate across specification than predicates, + and details like the exact order of elements returned from querySelector seem to make more sense being defined in the DOM specification than in Selectors.
+
Should it instead default to the root element, + to match the definition of :scope?
+
This is now redundant with the root elements.
+
Only the ::before and ::after pseudo-elements are really + handled in any way remotely like this.
+
The relative position of pseudo-elements + in selector match list is undefined. + There’s not yet a context that exposes this information, + but we need to decide on something eventually, + before something is exposed.
+
Some pseudo-classes are *syntactical*, + like :has() and :matches(), + and thus should always work. + Need to indicate that somewhere. + Probably the structural pseudos always work + whenever the child list is ordered.
+
Semantic definition should probably move back here.
+
Need to define tree for XML.
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test_new/browser/harness.test.ts b/test_new/browser/harness.test.ts new file mode 100644 index 0000000..a95817c --- /dev/null +++ b/test_new/browser/harness.test.ts @@ -0,0 +1,162 @@ +import { expect } from "@playwright/test"; +import { runScenarios } from "./harness/scenarios"; + +runScenarios('scope', 'normal', [ + { + name: 'classes', + markup: ` +
+
+
+ `, + cases: [ + { select: 'div', expect: { classes: ['outer primary', 'other-outer', ''] } }, + { select: 'div', expect: { includesClasses: ['other-outer'] } }, + { select: 'div', expect: { includesClasses: ['outer', 'primary'] } }, + { select: 'div', expect: { excludesClasses: ['missing-class'] } }, + ], + }, + + { + name: 'context-home', + markupMode: 'html-document', + markup: ` + + + +
+
+
+
+
+ +
+ +
+ + + `, + cases: [ + // Inherited state should differ by home + { match: ':lang(en)', ref: { by: 'id', id: 'lang-child' }, expect: { ids: ['lang-child'] } }, + { match: ':lang(en)', ref: { by: 'id', id: 'lang-child', home: 'detached' }, expect: { ids: [] } }, + { match: ':lang(en)', ref: { by: 'id', id: 'lang-child', home: 'fragment' }, expect: { ids: [] } }, + + // Element-local matching should survive rehoming + { match: '.foo', ref: { by: 'id', id: 'class-child' }, expect: { ids: ['class-child'] } }, + { match: '.foo', ref: { by: 'id', id: 'class-child', home: 'detached' }, expect: { ids: ['class-child'] } }, + { match: '.foo', ref: { by: 'id', id: 'class-child', home: 'fragment' }, expect: { ids: ['class-child'] } }, + + // Ancestor traversal depends on whether the ancestor chain is preserved + { closest: '.box', ref: { by: 'id', id: 'class-child' }, expect: { ids: ['class-parent'] } }, + { closest: '.box', ref: { by: 'id', id: 'class-child', home: 'detached' }, expect: { ids: [] } }, + { closest: '.box', ref: { by: 'id', id: 'class-child', home: 'fragment' }, expect: { ids: [] } }, + ], + }, + + { + name: 'equivalent cases that are detached should fail', + markupMode: 'html-document', + status: 'fail', + markup: ` + + + +
+
+ alpha +
+
+ + + + + `, + cases: [ + { + select: '.hit', + ref: { by: 'id', id: 'left', home: 'detached' }, + expect: { + count: 1, + equivalentCase: { + select: '.hit', + ref: { by: 'id', id: 'right', home: 'document' }, + }, + }, + }, + ], + }, + + { + name: 'setup page can be used to verify test assumptions', + markup: ` +
+
+ + `, + setupPage: async (page) => { + const result = await page.evaluate(() => ({ + divXCount: document.querySelectorAll('div.x').length, + spanCount: document.querySelectorAll('span').length, + })); + + expect(result.divXCount).toEqual(2); + expect(result.spanCount).toEqual(1); + }, + cases: [ + { select: 'div.x', expect: { count: 2 } }, + { select: 'span', expect: { count: 1 } }, + ] + }, + + { + name: 'steps/basic-accumulation', + markup: ` +
+ `, + steps: [ + { + setupPage: async (page) => { + await page.evaluate(() => { document.getElementById('box')!.classList.add('a'); }); + }, + cases: [ + { select: '#box.a', expect: { ids: ['box'] } }, + { select: '#box.b', expect: { ids: [] } }, + ], + }, + { + setupPage: async (page) => { + await page.evaluate(() => { document.getElementById('box')!.classList.add('b'); }); + }, + cases: [ + { select: '#box.a', expect: { ids: ['box'] } }, + { select: '#box.b', expect: { ids: ['box'] } }, + ], + }, + ], + }, + + { + name: 'xml-basic', + markupMode: 'xml-document', + markup: ` + + + + + `, + cases: [ + { select: 'Foo', expect: { count: 1 } }, + { select: 'foo', expect: { count: 0 } }, + { select: 'bar', expect: { count: 1 } }, + { select: 'Foo bar', expect: { count: 1 } }, + { select: 'foo bar', expect: { count: 0 } }, + { select: 'bar', ref: { by: 'id', id: 'upper' }, expect: { count: 1 } }, + ], + } + +]); \ No newline at end of file diff --git a/test_new/browser/harness/browser.ts b/test_new/browser/harness/browser.ts new file mode 100644 index 0000000..395a027 --- /dev/null +++ b/test_new/browser/harness/browser.ts @@ -0,0 +1,352 @@ +import { type Engine, type EquivalentCase, type ContextRef, type ContextHome, NwsapiId } from "./scenarios"; + +export interface PwHelpers { + resolveContext(doc:Document, ref?: ContextRef): QueryContext | null; + runQuery(query: () => Element[]): QueryResult; + compareQueryResults(a: NamedQueryResult, b: NamedQueryResult): string | undefined; + toEngineResult(res: QueryResult): EngineResult; + getResults(queryFn: EngineQuery, query: string, ctx: QueryContext | null, ctxErrorMsg?: string): EngineAndQueryResult; + getEngineQuery(c: EquivalentCase, n: Engine): EngineQuery; + getCaseQuery(c: EquivalentCase): string; + getCaseLabel(c: EquivalentCase, n: Engine): string; + stringify(obj: unknown): string; + isRehomed(ref?: ContextRef): boolean; +} + +export type EvalResult = { + info: string; + mismatchMsg?: string; + equivMismatchMsg?: string; + engineResults: Partial>; +}; + +export type EngineResult = { + count: number; + ids: string[]; + classes: string[]; + threw: boolean; +}; + +export type EngineQuery = (query: string, ctx: QueryContext) => () => Element[]; +export type EngineAndQueryResult = { queryResult: QueryResult; engineResult: EngineResult; }; +export type NamedQueryResult = { name: string; result: QueryResult; }; +export type QueryResult = { elements: Element[]; error: string }; + +export function installBrowserHelpers(): void { + function assertNever(x: never): never { + throw new Error(`Unexpected key: ${x}`); + } + + function isElement(x: unknown): x is Element { + return typeof x === 'object' && x !== null && 'nodeType' in x && x.nodeType === 1; + } + + function isDocument(x: unknown): x is Document { + return typeof x === 'object' && x !== null && 'nodeType' in x && x.nodeType === 9; + } + + function isDocFrag(x: unknown): x is DocumentFragment { + return typeof x === 'object' && x !== null && 'nodeType' in x && x.nodeType === 11; + } + + function isRehomed(ref?: ContextRef): boolean { + if (!ref) return false; + if ('within' in ref && isRehomed(ref.within)) return true; + return 'home' in ref && !!ref.home && ref.home !== 'document'; + } + + // Source - https://stackoverflow.com/a/65443215 + function stringify(obj: unknown): string { + let json = JSON.stringify(obj, null, 2) as string | undefined; + if (json === undefined) return String(obj); + json = json.replace(/^[\t ]*"[^:\n\r]+(? Element[]) { + try { + const id: NwsapiId = 'nwsapi-bootstrap'; + const els = query().filter((el) => el.getAttribute('id') !== id); + return { elements: els, error: '' }; + } catch (e) { + return { elements: [], error: e instanceof Error ? e.message : String(e) }; + } + } + + function describe(el: Element | undefined) { + if (!el) return '(missing)'; + const id = el.getAttribute('id'); + const className = el.getAttribute('class'); + return `<${el.tagName.toLowerCase()}${id ? ` id='${id}'` : ''}${className ? ` class='${className}'` : ''}>`; + } + + function compareQueryResults(a: NamedQueryResult, b: NamedQueryResult): string | undefined { + if (a.result.error || b.result.error) { + if (a.result.error && b.result.error) { + return `Both threw:\n ${a.name} error: ${a.result.error}\n ${b.name} error: ${b.result.error}`; + } + return a.result.error + ? `Throw mismatch:\n ${a.name} threw while ${b.name} did not.\n error: ${a.result.error}` + : `Throw mismatch:\n ${b.name} threw while ${a.name} did not.\n error: ${b.result.error}`; + } + + const aElems = a.result.elements; + const bElems = b.result.elements; + + let mismatchMsg: string | undefined; + if (aElems.length !== bElems.length) { + mismatchMsg = `Count mismatch:\n ${a.name} = ${aElems.length}\n ${b.name} = ${bElems.length}`; + } + + const maxLen = Math.max(aElems.length, bElems.length); + for (let i = 0; i < maxLen; ++i) { + if (aElems[i] !== bElems[i]) { + mismatchMsg = mismatchMsg ? mismatchMsg + '\n' : ''; + mismatchMsg += `First element mismatch at index ${i}:\n` + + ` ${a.name}[${i}] = ${describe(aElems[i])}\n` + + ` ${b.name}[${i}] = ${describe(bElems[i])}`; + break; + } + } + + return mismatchMsg; + } + + function queryId(base: QueryContext, id: string): Element | null { + if ('getElementById' in base && typeof base.getElementById === 'function') { + return base.getElementById(id); + } + return base.querySelector(`#${CSS.escape(id)}`); + } + + function resolveContext(doc: Document, ref?: ContextRef): QueryContext | null { + if (!ref || ref.by === 'document') return doc; + + const base = 'within' in ref && ref.within ? resolveContext(doc, ref.within) : doc; + if (!base) return null; + + if (ref.by === 'iframe') { + const iframe = queryId(base, ref.id); + if (!(iframe instanceof HTMLIFrameElement)) return null; + return iframe.contentDocument ?? null; + } + + if (ref.by === 'template') { + const tmpl = queryId(base, ref.id); + if (!(tmpl instanceof HTMLTemplateElement)) return null; + return tmpl.content; + } + + const el = ref.by === 'id' ? queryId(base, ref.id) + : ref.by === 'first' ? base.querySelector(ref.selector) + : ref.by === 'documentElement' ? doc.documentElement + : null; + + if (!el) return null; + + const home: ContextHome = ref.home ?? 'document'; + if (home === 'document') return el; + + const clone = el.cloneNode(true); + if (!isElement(clone)) return null; + if (home === 'detached') return clone; + + if (home === 'fragment') { + const frag = doc.createDocumentFragment(); + frag.appendChild(clone); + + // Return the clone rehomed so matches/closest stay sane. + return clone; + } + + return null; + } + + function toEngineResult(res: QueryResult): EngineResult { + return { + count: res.elements.length, + ids: res.elements.map((el) => el.getAttribute('id') ?? ''), + classes: res.elements.map((el) => el.getAttribute('class') ?? ''), + threw: !!res.error, + }; + } + + function getResults(queryFn: EngineQuery, query: string, ctx: QueryContext | null, ctxErrorMsg?: string): EngineAndQueryResult { + const queryResult: QueryResult = ctx + ? runQuery(queryFn(query, ctx)) + : { elements: [], error: ctxErrorMsg ?? 'No context provided' }; + + const engineResult = toEngineResult(queryResult); + return { queryResult, engineResult }; + } + + function getEngineQuery(c: EquivalentCase, ng: Engine): EngineQuery { + switch (true) { + case 'select' in c: + if (ng === 'native') return (query, ctx) => () => [...ctx.querySelectorAll(query)]; + if (ng === 'nw') return (query, ctx) => () => NW.Dom.select(query, ctx); + break; + + case 'first' in c: + if (ng === 'native') { + return (query, ctx) => () => { + const el = ctx.querySelector(query); + return el ? [el] : []; + }; + } + if (ng === 'nw') { + return (query, ctx) => () => { + const el = NW.Dom.first(query, ctx); + return el ? [el] : []; + }; + } + break; + + case 'byTag' in c: + if (ng === 'native') { + return (query, ctx) => () => + isDocFrag(ctx) + ? [...ctx.querySelectorAll(query)] + : [...ctx.getElementsByTagName(query)]; + } + if (ng === 'nw') return (query, ctx) => () => NW.Dom.byTag(query, ctx); + break; + + case 'byClass' in c: + if (ng === 'native') { + return (query, ctx) => () => + isDocFrag(ctx) + ? [...ctx.querySelectorAll(`.${query}`)] + : [...ctx.getElementsByClassName(query)]; + } + if (ng === 'nw') return (query, ctx) => () => NW.Dom.byClass(query, ctx); + break; + + case 'byId' in c: + if (ng === 'native') { + return (query, ctx) => () => { + const useFragmentBase = c.ref && 'home' in c.ref && c.ref.home === 'fragment' && isDocFrag(ctx.parentNode); + const base = useFragmentBase ? ctx.parentNode : ctx; + const el = isElement(base) + ? base.querySelector(`#${CSS.escape(query)}`) + : base.getElementById(query); + + return el ? [el] : []; + }; + } + if (ng === 'nw') return (query, ctx) => () => NW.Dom.byId(query, ctx); + break; + + case 'match' in c: + if (ng === 'native') { + return (query, ctx) => () => { + if (!isElement(ctx)) throw new Error(`Context for 'match' case must be an Element`); + const el = ctx; + return el.matches(query) ? [el] : []; + }; + } + if (ng === 'nw') { + return (query, ctx) => () => { + if (!isElement(ctx)) throw new Error(`Context for 'match' case must be an Element`); + const el = ctx; + return NW.Dom.match(query, el) ? [el] : []; + }; + } + break; + + case 'closest' in c: + if (ng === 'native') { + return (query, ctx) => () => { + if (!isElement(ctx)) throw new Error(`Context for 'closest' case must be an Element`); + const el = ctx; + const hit = el.closest(query); + return hit ? [hit] : []; + }; + } + if (ng === 'nw') { + return (query, ctx) => () => { + if (!isElement(ctx)) throw new Error(`Context for 'closest' case must be an Element`); + const el = ctx; + const hit = NW.Dom.closest(query, el); + return hit ? [hit] : []; + }; + } + break; + + default: + throw assertNever(c); + } + + throw assertNever(ng); + } + + function getCaseQuery(c: EquivalentCase): string { + switch (true) { + case 'select' in c: return c.select; + case 'first' in c: return c.first; + case 'byTag' in c: return c.byTag; + case 'byClass' in c: return c.byClass; + case 'byId' in c: return c.byId; + case 'match' in c: return c.match; + case 'closest' in c: return c.closest; + default: throw assertNever(c); + } + } + + function getCaseLabel(c: EquivalentCase, engine: Engine): string { + switch (true) { + case 'select' in c: + return engine === 'native' + ? `querySelectorAll(${c.select})` + : `NW.Dom.select(${c.select})`; + + case 'first' in c: + return engine === 'native' + ? `querySelector(${c.first})` + : `NW.Dom.first(${c.first})`; + + case 'byTag' in c: + return engine === 'native' + ? `byTag:${c.byTag}` + : `NW.Dom.byTag(${c.byTag})`; + + case 'byClass' in c: + return engine === 'native' + ? `byClass:${c.byClass}` + : `NW.Dom.byClass(${c.byClass})`; + + case 'byId' in c: + return engine === 'native' + ? `byId:${c.byId}` + : `NW.Dom.byId(${c.byId})`; + + case 'match' in c: + return engine === 'native' + ? `matches(${c.match})` + : `NW.Dom.match(${c.match})`; + + case 'closest' in c: + return engine === 'native' + ? `closest(${c.closest})` + : `NW.Dom.closest(${c.closest})`; + + default: + throw assertNever(c); + } + } + + window.__pwHelpers = { + resolveContext, + runQuery, + compareQueryResults, + toEngineResult, + getResults, + getEngineQuery, + getCaseQuery, + getCaseLabel, + stringify, + isRehomed, + }; +}; diff --git a/test_new/browser/harness/scenarios.ts b/test_new/browser/harness/scenarios.ts new file mode 100644 index 0000000..771f0e8 --- /dev/null +++ b/test_new/browser/harness/scenarios.ts @@ -0,0 +1,557 @@ +import { test, chromium, expect, firefox, webkit } from '@playwright/test'; +import type { Browser, Page } from '@playwright/test'; +import { assertNever, type Permutations, type DistributiveOmit } from '../../utils/type'; +import { installBrowserHelpers } from './browser'; +import type { EngineResult, EvalResult, EngineAndQueryResult, NamedQueryResult } from './browser'; + +type HarnessMode = 'normal' | 'fixme'; +const rawHarnessMode = process.env.HARNESS_MODE; +if (rawHarnessMode !== undefined && rawHarnessMode !== 'normal' && rawHarnessMode !== 'fixme') { + throw new Error(`Invalid HARNESS_MODE: ${rawHarnessMode}`); +} +const HARNESS_MODE: HarnessMode = rawHarnessMode ?? 'normal'; + +export type SelectCase = { select: string; ref?: ContextRef; } & CaseBase; +export type ByIdCase = { byId: string; ref?: ContextRef; } & CaseBase; +export type ByTagCase = { byTag: string; ref?: ContextRef; } & CaseBase; +export type ByClassCase = { byClass: string; ref?: ContextRef; } & CaseBase; +export type FirstCase = { first: string; ref?: ContextRef; } & CaseBase; +export type MatchCase = { match: string; ref: ContextRef; } & CaseBase; +export type ClosestCase = { closest: string; ref: ContextRef; } & CaseBase; + +type CaseBase = { + expect?: Expectation; + status?: CaseStatus; + browsers?: BrowserName[]; + engines?: Engine[]; +}; + +export type TestCase = SelectCase | ByIdCase | ByTagCase | ByClassCase | MatchCase | FirstCase | ClosestCase; + +export type Scenario = { + name: string; + status?: ScenarioStatus; + markup: string; + markupMode?: 'html-body' | 'html-document' | 'xml-document'; + url?: string; + browsers?: BrowserName[]; + engines?: Engine[]; + steps?: ScenarioStep[]; + + // ergonomic sugar for simple scenarios that don't require multiple steps + setupPage?: (page: Page) => void | Promise; + cases?: TestCase[]; +}; + +type ScenarioStep = { + setupPage?: (page: Page) => void | Promise; + cases: TestCase[]; +}; + +export type Expectation = { + count?: number; + ids?: string[]; + includesIds?: string[]; + excludesIds?: string[]; + classes?: string[]; + includesClasses?: string[]; + excludesClasses?: string[]; + throws?: boolean; + equivalentCase?: EquivalentCase; +}; + +export type EquivalentCase = DistributiveOmit; +// const foo: EquivalentCase = { select: 'div' }; // just to verify the type + +const BROWSER_NAMES = ['chromium', 'firefox', 'webkit'] as const; +type BrowserName = typeof BROWSER_NAMES[number]; + +type ScenariosStatus = 'normal' | 'skip' | 'only'; // | 'fixme'; +type ScenarioStatus = 'normal' | 'skip' | 'only' | 'fixme' | 'fail'; +type CaseStatus = 'normal' | 'skip' | 'fixme' | 'fail' | 'only'; + +export const ENGINES = ['native', 'nw'] as const; +export type Engine = typeof ENGINES[number]; + +export type ContextRef = + | { by: 'document' } + | { by: 'id'; id: string; home?: ContextHome; within?: ContextRef } + | { by: 'first'; selector: string; home?: ContextHome; within?: ContextRef } + | { by: 'documentElement'; home?: ContextHome; } + | { by: 'iframe'; id: string; within?: ContextRef } + | { by: 'template'; id: string; within?: ContextRef } + +export type ContextHome = 'document' | 'detached' | 'fragment'; +export type NwsapiId = 'nwsapi-bootstrap'; + +type PassTracker = { passedEverywhere: boolean; resultInfo: string; stepIndex: number; caseIndex: number; }; + +type CaseInfo = { + browser: BrowserName; + scenario: Scenario; + case: TestCase; + stepIndex: number; + caseIndex: number; + stepCaseIndex: number; + misfails: Record; + misfixes: Record; +}; + +export function runScenarios(label: string, status: ScenariosStatus, scenarios: Scenario[]): void { + const describeFn = getDescribeFn(status); + describeFn(label, () => { + let browsers: Record; + let pages: Record; + + test.beforeAll(async () => { + browsers = { + chromium: await chromium.launch(), + firefox: await firefox.launch(), + webkit: await webkit.launch(), + }; + + pages = { + chromium: await browsers.chromium.newPage(), + firefox: await browsers.firefox.newPage(), + webkit: await browsers.webkit.newPage(), + }; + + for (const page of Object.values(pages)) { + await page.setContent(''); + } + }); + + test.afterAll(async () => { + await Promise.all(BROWSER_NAMES.map((name) => browsers[name].close())); + }); + + const scenarioHas = (s: Scenario, status: 'only' | 'fixme'): boolean => + s.status === status || + !!s.cases?.some(c => c.status === status) || + !!s.steps?.some(step => step.cases.some(c => c.status === status)); + + const hasScenariosOnly = scenarios.some(s => scenarioHas(s, 'only')); + + for (const s of scenarios) { + const hasFixme = scenarioHas(s, 'fixme'); + if (HARNESS_MODE === 'fixme' && !hasFixme) continue; + + const hasOnly = scenarioHas(s, 'only'); + if (hasScenariosOnly && !hasOnly) continue; + + const testFn = getTestFn(s.status); + testFn(s.name, async () => { + await runScenario(s, pages); + }); + } + }); +} + +async function runScenario(s: Scenario, pages: Record): Promise { + const scenarioBrowsers = s.browsers ?? BROWSER_NAMES; + + // cases marked fail/fixme and whether they passed in every applicable browser so far + const misfails: Record = {}; + const misfixes: Record = {}; + + const steps: ScenarioStep[] = [ + ...(s.steps ?? []), + ...(s.cases?.length ? [{ cases: s.cases }] : []), + ]; + + const hasOnlyCases = steps.some(step => step.cases.some(c => c.status === 'only')); + + for (const browserName of scenarioBrowsers) { + const page = pages[browserName]; + const wrappedPage = s.markupMode === 'xml-document' ? wrapPageForXml(page) : page; + + await initPage(wrappedPage, s); + + let stepCaseIndex = 0; + for (let stepIndex = 0; stepIndex < steps.length; ++stepIndex) { + const step = steps[stepIndex]; + if (step.setupPage) await step.setupPage(wrappedPage); + ensureHarnessInstalled(wrappedPage); + for (let caseIndex = 0; caseIndex < step.cases.length; ++caseIndex) { + const c = step.cases[caseIndex]; + if (hasOnlyCases && c.status !== 'only') continue; + await runCase( + page, + { + browser: browserName, scenario: s, case: c, + stepIndex, caseIndex, stepCaseIndex, misfails, misfixes, + } + ); + stepCaseIndex++; + } + } + } + + // At the end of the scenario, check if any 'fail' or 'fixme' cases passed unexpectedly + const throwOnUnexpectedPass = (kind: 'fail' | 'fixme', trackers: Record) => { + for (const tracker of Object.values(trackers)) { + if (!tracker.passedEverywhere) continue; + throw new Error( + `${s.name}\n` + + `Step #${tracker.stepIndex + 1}, Case #${tracker.caseIndex + 1} · Marked '${kind}' but passed unexpectedly.\n` + + `Query: ${tracker.resultInfo}` + ); + } + }; + + throwOnUnexpectedPass('fail', misfails); + throwOnUnexpectedPass('fixme', misfixes); +} + +async function runCase(page: Page, caseInfo: CaseInfo): Promise { + const { scenario: s, case: c, stepIndex, caseIndex, stepCaseIndex } = caseInfo; + + if (c.status === 'skip') return; + if (s.status !== 'fixme' && HARNESS_MODE === 'fixme' && c.status !== 'fixme') { + return; + } + if (c.browsers && !c.browsers.includes(caseInfo.browser)) return; + c.engines = c.engines ?? s.engines; + + const result = await evalCase(page, caseInfo); + const expectation = c.expect ?? {}; + + let thrown: unknown = undefined; + try { + checkResult(result, expectation, caseInfo); + } catch (err) { + thrown = err; + } + + const status = c.status ?? 'normal'; + + if (status === 'normal' || status === 'only') { + if (thrown) throw thrown; + return; + } + + const updatePassTracker = (trackers: Record) => { + const prevPassed = trackers[stepCaseIndex]?.passedEverywhere ?? true; + trackers[stepCaseIndex] = { + passedEverywhere: !thrown && prevPassed, + resultInfo: trackers[stepCaseIndex]?.resultInfo ?? result.info, + stepIndex, + caseIndex, + }; + }; + + if (status === 'fail') { + updatePassTracker(caseInfo.misfails); + return; + } + + if (status === 'fixme') { + updatePassTracker(caseInfo.misfixes); + if (thrown && HARNESS_MODE === 'fixme') throw thrown; + return; + } + + assertNever(status); +} + +async function evalCase(page: Page, caseInfo: CaseInfo): Promise { + const { scenario: s, case: c } = caseInfo; + return await page.evaluate(({c, isXml} ) => { + const pw = window.__pwHelpers; + const doc = isXml ? window.__pwXml : window.document; + + const query = pw.getCaseQuery(c); + const ctx = pw.resolveContext(doc, c.ref); + const ctxErrorMsg = ctx ? undefined : `Could not resolve context from ref: ${pw.stringify(c.ref)}`; + + const equivCase = c.expect?.equivalentCase; + const equivQuery = equivCase ? pw.getCaseQuery(equivCase) : undefined; + const equivCtx = equivCase ? pw.resolveContext(doc, equivCase?.ref) : null; + const equivCtxErrorMsg = equivCase && !equivCtx + ? `Could not resolve equivalent context from ref: ${pw.stringify(equivCase.ref)}` + : undefined; + let equivMismatchMsg = equivCase && (pw.isRehomed(c.ref) || pw.isRehomed(equivCase.ref)) + ? `Equivalent-case assertion unsupported because one or more contexts were rehomed.\n` + + `Identity-based equivalence is only supported for document-backed contexts.\n` + + ` case context: ${pw.stringify(c.ref)}${pw.isRehomed(c.ref) ? ' (rehomed)' : ''}\n` + + ` equivalent case context: ${pw.stringify(equivCase.ref)}${pw.isRehomed(equivCase.ref) ? ' (rehomed)' : ''}` + : undefined; + + const allEngines: Permutations = ['native', 'nw']; + const engines = c.engines ?? allEngines; + const engineResults: Partial> = {}; + const makeNamedQr = (tc: TestCase, ng: Engine, res: EngineAndQueryResult, suffix = ''): NamedQueryResult => + ({ name: `${ng}${suffix}:${pw.getCaseLabel(tc, ng)}`, result: res.queryResult }); + + let mismatchMsg: string | undefined; + let firstNamedQr: NamedQueryResult | undefined; + + for (const engine of engines) { + const fn = pw.getEngineQuery(c, engine); + const res = pw.getResults(fn, query, ctx, ctxErrorMsg); + engineResults[engine] = res; + + const namedQr = makeNamedQr(c, engine, res); + if (!mismatchMsg && firstNamedQr) { + mismatchMsg = pw.compareQueryResults(firstNamedQr, namedQr); + } + firstNamedQr ??= namedQr; + + if (!equivMismatchMsg && equivCase && equivQuery) { + const equivFn = pw.getEngineQuery(equivCase, engine); + const equivRes = pw.getResults(equivFn, equivQuery, equivCtx, equivCtxErrorMsg); + equivMismatchMsg ??= pw.compareQueryResults( + namedQr, + makeNamedQr(equivCase, engine, equivRes, 'Equiv') + ); + } + } + + return { + info: query, mismatchMsg, equivMismatchMsg, + engineResults: Object.fromEntries( + engines.map((engine) => [engine, engineResults[engine]!.engineResult]) + ), + }; + }, {c: caseInfo.case, isXml: s.markupMode === 'xml-document' }); +} + +function getDescribeFn(mode?: ScenariosStatus) { + if (mode === 'skip') return test.describe.skip; + if (mode === 'only') return test.describe.only; + // if (mode === 'fixme') return test.describe.fixme; + return test.describe; +} + +function getTestFn(mode?: ScenarioStatus) { + if (mode === 'skip') return test.skip; + if (mode === 'only') return test.only; + if (mode === 'fixme') { + if (HARNESS_MODE === 'fixme') return test; + return test.fixme; + } + if (mode === 'fail') return test.fail; + return test; +} + +async function initPage(page: Page, scenario: Scenario): Promise { + if (scenario.url && page.url() !== scenario.url) { + await page.route(scenario.url, async route => { + await route.fulfill({ + status: 200, + contentType: 'text/html', + body: '', + }); + }); + + await page.goto(scenario.url); + } + + await ensureHarnessInstalled(page); + + if (scenario.markupMode === 'xml-document') { + await page.setContent(`dummy content`); + await page.evaluate((xmlString) => { + const xml = new DOMParser().parseFromString(xmlString, 'text/xml'); + if (xml.getElementsByTagName('parsererror').length) { + throw new Error(`invalid xml-document markup: ${xml.documentElement?.textContent ?? 'parsererror'}`); + } + window.__pwXml = xml; + }, scenario.markup); + } else if (scenario.markupMode === 'html-document') { + await page.setContent(scenario.markup); + await installNwsapi(page); + } else if (scenario.markupMode === 'html-body' || !scenario.markupMode) { + await page.evaluate((bodyHtml) => { + document.body.innerHTML = bodyHtml; + }, scenario.markup); + } else { + assertNever(scenario.markupMode); + } + + if (scenario.setupPage) { + await scenario.setupPage(page); + await ensureHarnessInstalled(page); + } +} + +async function ensureHarnessInstalled(page: Page): Promise { + const state = await page.evaluate(() => ({ + hasHelpers: !!window.__pwHelpers, + hasNwsapi: !!NW?.Dom, + })).catch(() => ({ hasHelpers: false, hasNwsapi: false })); + + if (!state.hasHelpers) { + await page.evaluate(installBrowserHelpers); + } + + if (!state.hasNwsapi) { + await page.addScriptTag({ path: 'src/nwsapi.js' }); + } +} + +async function installNwsapi(page: Page): Promise { + const script = await page.addScriptTag({ path: 'src/nwsapi.js' }); + await script.evaluate((el) => { + (el as HTMLScriptElement).id = 'nwsapi-bootstrap' satisfies NwsapiId; + }); +} + +function runEngineChecks( + result: EvalResult, + baseMsg: string, + key: keyof EngineResult, + check: (r: EngineResult, label: string) => void +): void { + const entries = Object.entries(result.engineResults) as [Engine, EngineResult][]; + + const sameIds = (a: string[], b: string[]): boolean => + a.length === b.length && a.every((x, i) => x === b[i]); + + for (const [, r] of entries) { + const enginesWithSameOutcome = entries + .filter(([, other]) => { + switch (key) { + case 'count': return r.count === other.count; + case 'ids': return sameIds(r.ids, other.ids); + case 'classes': return sameIds(r.classes, other.classes); + case 'threw': return r.threw === other.threw; + default: return assertNever(key); + } + }) + .map(([engine]) => engine); + + const engineLabel = ` · Engines=${enginesWithSameOutcome.join('+')}${baseMsg}`; + check(r, engineLabel); + } +} + +function checkResult(result: EvalResult, expectation: Expectation, caseInfo: CaseInfo): void { + const { stepIndex, caseIndex, browser, scenario: s } = caseInfo; + const header = `${s.name}\nStep #${stepIndex + 1}, Case #${caseIndex + 1} · Browser=${browser}`; + const msg = + `\nQuery: ${result.info}` + + `\nContext: ${formatContextRef(caseInfo.case.ref)}` + + `${result.mismatchMsg ? `\n\n${result.mismatchMsg}` : ''}`; + + runEngineChecks(result, msg, 'threw', (r, nglabel) => { + const errLabel = `Expected ${expectation.throws ? 'a throw' : 'no throw'}, got ${r.threw ? 'a throw' : 'no throw'}.`; + expect(r.threw, `${errLabel}\n\n${header}${nglabel}`).toBe(expectation.throws ?? false); + }); + if (expectation.throws) return; + + if (expectation.count !== undefined) { + runEngineChecks(result, msg, 'count', (r, ngLabel) => { + const errLabel = `Expected count ${expectation.count}, got ${r.count}.`; + expect(r.count, `${errLabel}\n\n${header}${ngLabel}`).toEqual(expectation.count); + }); + } + + if (expectation.ids) { + runEngineChecks(result, msg, 'ids', (r, ngLabel) => { + const errLabel = `Expected ids ${JSON.stringify(expectation.ids)}, got ${JSON.stringify(r.ids)}.`; + expect(r.ids, `${errLabel}\n\n${header}${ngLabel}`).toEqual(expectation.ids); + }); + } + + if (expectation.includesIds) { + for (const id of expectation.includesIds) { + runEngineChecks(result, msg, 'ids', (r, ngLabel) => { + const errLabel = `Expected ids to include ${JSON.stringify(id)}, got ${JSON.stringify(r.ids)}.`; + expect(r.ids, `${errLabel}\n\n${header}${ngLabel}`).toContain(id); + }); + } + } + + if (expectation.excludesIds) { + for (const id of expectation.excludesIds) { + runEngineChecks(result, msg, 'ids', (r, ngLabel) => { + const errLabel = `Expected ids not to include ${JSON.stringify(id)}, got ${JSON.stringify(r.ids)}.`; + expect(r.ids, `${errLabel}\n\n${header}${ngLabel}`).not.toContain(id); + }); + } + } + + if (expectation.classes) { + runEngineChecks(result, msg, 'classes', (r, ngLabel) => { + const errLabel = `Expected classes ${JSON.stringify(expectation.classes)}, got ${JSON.stringify(r.classes)}.`; + expect(r.classes, `${errLabel}\n\n${header}${ngLabel}`).toEqual(expectation.classes); + }); + } + + if (expectation.includesClasses) { + for (const cls of expectation.includesClasses) { + runEngineChecks(result, msg, 'classes', (r, ngLabel) => { + const errLabel = `Expected classes to include ${JSON.stringify(cls)}, got ${JSON.stringify(r.classes)}.`; + const classTokens = r.classes.flatMap(s => s.trim() ? s.trim().split(/\s+/) : []); + expect(classTokens, `${errLabel}\n\n${header}${ngLabel}`).toContain(cls); + }); + } + } + + if (expectation.excludesClasses) { + for (const cls of expectation.excludesClasses) { + runEngineChecks(result, msg, 'classes', (r, ngLabel) => { + const errLabel = `Expected classes not to include ${JSON.stringify(cls)}, got ${JSON.stringify(r.classes)}.`; + const classTokens = r.classes.flatMap(s => s.trim() ? s.trim().split(/\s+/) : []); + expect(classTokens, `${errLabel}\n\n${header}${ngLabel}`).not.toContain(cls); + }); + } + } + + expect(!!result.mismatchMsg, `Expected engine agreement, but they differed.\n\n${header}${msg}`).toBe(false); + + if (expectation.equivalentCase) { + const errLabel = `Expected this case to match its equivalent case, but it did not.`; + const equivMismatch = !!result.equivMismatchMsg; + expect(equivMismatch, `${errLabel}\n\n${header}${msg}\n${result.equivMismatchMsg}`).toBe(false); + } +} + +function formatContextRef(ref?: ContextRef): string { + if (!ref) return 'document'; + let base: string; + switch (ref.by) { + case 'document': base = 'document'; break; + case 'id': base = `id(${ref.id})`; break; + case 'first': base = `first(${ref.selector})`; break; + case 'documentElement': base = 'documentElement'; break; + case 'iframe': base = `iframe(${ref.id})`; break; + case 'template': base = `template(${ref.id})`; break; + default: assertNever(ref); + } + if ('home' in ref && ref.home) base += `:${ref.home}`; + if ('within' in ref && ref.within) base = `${formatContextRef(ref.within)} > ${base}`; + return base; +} + +function wrapPageForXml(page: Page): Page { + return new Proxy(page, { + get(target, prop, receiver) { + if (prop !== 'evaluate') return Reflect.get(target, prop, receiver); + + return async (fn: unknown, arg?: unknown) => { + if (typeof fn !== 'function') { + throw new Error('xml proxy currently supports only function evaluate callbacks'); + } + + const fnSource = fn.toString(); + + return target.evaluate(({ fnSource, arg }) => { + window.__pwArg = arg; + try { + return eval(` + (() => { + const document = window.__pwXml; + const fn = (${fnSource}); + return fn(window.__pwArg); + })() + `); + } finally { + delete window.__pwArg; + } + }, { fnSource, arg }); + }; + }, + }) as Page; +} diff --git a/test_new/browser/html5.test.ts b/test_new/browser/html5.test.ts new file mode 100644 index 0000000..9ef350b --- /dev/null +++ b/test_new/browser/html5.test.ts @@ -0,0 +1,199 @@ +import { runScenarios } from "./harness/scenarios"; + +runScenarios('html5', 'normal', [ + { + name: 'html5 elements selection test', + markup: ` +

NWSAPI HTML5 elements selection test

+ +

Usual nonsense content...

+ +

+ IBA + Located at 116 Messina Avenue, London NW6 4LD + UK +

+ +
+
    +
  • First
  • +
  • Second
  • +
  • Last
  • +
+
+ +
+ `, + cases: [ + { select: 'abbr:first-of-type', expect: { ids: ['IBA'] } }, + { select: 'abbr:last-of-type', expect: { ids: ['UK'] } }, + { select: 'mark:only-of-type', expect: { ids: ['NUM'] } }, + { select: 'abbr:nth-of-type(1)', expect: { ids: ['IBA'] } }, + { select: 'abbr:nth-of-type(2)', expect: { ids: ['UK'] } }, + { select: 'abbr:nth-last-of-type(1)', expect: { ids: ['UK'] } }, + { select: 'abbr:nth-last-of-type(2)', expect: { ids: ['IBA'] } }, + { select: 'section li:first-of-type', expect: { ids: ['first'] } }, + { select: 'section li:last-of-type', expect: { ids: ['last'] } }, + ], + }, + + { + name: 'table :not() selector test', + markup: ` +
+

 Your Search Results

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
You searched for: all records
Showing matches 1 to 10 of 1405
 
PhotoReg Number Make & ModelColourStolen From Date / Time stolen 
AV11UXAMercedes-benz E Class Convertible White
London23rd April 2015 Between midday and 3pm
+
+
LD64FKOHonda CB500F Black
London22nd April 2015 in the afternoon
+
+
YN58 LXVPeugeot XPS CT 125 Black
Shropshire20th April 2015 Between midnight and 3am
+
+
YA08JZRPEUYGEOT PARTNER ORIGIN White
Staffordshire17th April 2015 Between 3am and 6am
+
+
DF03 KXBBaimo RSR 125 Blue
Hampshire19th April 2015 Between midnight and 3am
+
+
YG62 CM0Audi A4 Grey
West Midlands14th April 2015 Between midnight and 3am
+
+
FT10 FDVSeat Ibiza White
South Yorkshire9th April 2015 in the afternoon
+
+
RJ61 WREVolkswagen Golf 1.6 TDi Bluemotion Tech Match Red
Dyfed5th March 2015 Between 3pm and 6pm
+
+
SR11 HLOMazda Mazda3 Takuya Silver
London2nd April 2015 Between 9pm and midnight
+
+
TNZ 9284Citroen Berlingo GB9HXC White
Bedfordshire16th March 2015 time unknown
+
+
+
+ `, + cases: [ + { + select: 'tbody > tr:nth-of-type(n+6):not(:nth-of-type(17)) > td:nth-of-type(2) > a:not(:nth-of-type(2))', + expect: { ids: ['AV11UXA'] }, + status: 'fixme', + }, + ], + }, +]); \ No newline at end of file diff --git a/test_new/browser/issues.test.ts b/test_new/browser/issues.test.ts new file mode 100644 index 0000000..6e6a83d --- /dev/null +++ b/test_new/browser/issues.test.ts @@ -0,0 +1,21 @@ +import { runScenarios } from "./harness/scenarios"; + +runScenarios('issues', 'normal', [ + { + name: 'issue 160 adjacent-descendant regression', + markup: ` +
+
+
+ + + +
+
+ `, + cases: [ + { select: '.neighbor + div .target', expect: { count: 1 } }, + { select: '.neighbor + * .target', expect: { count: 1 }, status: 'fixme' }, + ], + }, +]); \ No newline at end of file diff --git a/test_new/browser/jquery.test.ts b/test_new/browser/jquery.test.ts new file mode 100644 index 0000000..02b2d16 --- /dev/null +++ b/test_new/browser/jquery.test.ts @@ -0,0 +1,924 @@ +import { expect, type Page } from "@playwright/test"; +import { runScenarios } from "./harness/scenarios"; + +const html = ` + + + + + jQuery Test Suite + + + + + +

jQuery Test Suite

+ +
+

+ + +
+
+
+ + + + + +
+
+
+ fadeIn +
fadeIn
+
+
+ fadeOut +
fadeOut
+
+ +
+ show +
show
+
+
+ hide +
hide
+
+ +
+ togglein +
togglein
+
+
+ toggleout +
toggleout
+
+ +
+ slideUp +
slideUp
+
+
+ slideDown +
slideDown
+
+ +
+ slideToggleIn +
slideToggleIn
+
+
+ slideToggleOut +
slideToggleOut
+
+
+ +
+
+ +
    + + +`; + +runScenarios('jquery', 'normal', [ + { + name: 'element selectors', + markup: html, + markupMode: 'html-document', + cases: [ + // Compare universal selection directly against native behavior. + { select: '*' }, + + { select: 'p', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'body', expect: { ids: ['body'] } }, + { select: 'html', expect: { ids: ['html'] } }, + { select: 'div p', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + + // scoped selection + { select: 'param', ref: { by: 'id', id: 'object1' }, expect: { count: 2 } }, + + // Consistency checks for multiple selector groups + { select: 'div p', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'div p', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'div p', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + + { select: '#length', expect: { count: 1 } }, + { select: '#lengthtest input', expect: { count: 2 } }, + + // Duplicate / sort-order checks from the original suite, expressed as counts. + { select: '*', expect: { count: 187 } }, + { select: '*, *', expect: { count: 187 } }, + { select: '*', expect: { equivalentCase: { select: '*, *' } } }, + + { select: 'p', expect: { count: 6 } }, + { select: 'p, div p', expect: { count: 6 } }, + { select: 'p', expect: { equivalentCase: { select: 'div p' } } }, + + { select: 'h2, h1', expect: { ids: ['header', 'banner', 'userAgent'] } }, + { select: 'p, p a', expect: { ids: ['firstp', 'simon1', 'ap', 'google', 'groups', 'anchor1', 'mark', 'sndp', 'en', 'yahoo', 'sap', 'anchor2', 'simon', 'first'] } }, + + // jQuery extension pseudo, not native CSS + // { selector: 'h2:first, h1:first', expect: { ids: ['header', 'banner'] } }, + ], + }, + + { + name: 'broken selectors', + markup: html, + markupMode: 'html-document', + cases: [ + { select: '[', expect: { throws: true } }, + { select: '(', expect: { throws: true } }, + { select: '{', expect: { throws: true } }, + { select: '<', expect: { throws: true } }, + { select: '()', expect: { throws: true } }, + { select: '{}', expect: { throws: true } }, + { select: '<>', expect: { throws: true } }, + + { select: ':nth-child(2n+-0)', expect: { throws: true } }, + { select: ':nth-child(- 1n)', expect: { throws: true } }, + { select: ':nth-child(-1 n)', expect: { throws: true } }, + { select: ':first-child(n)', expect: { throws: true } }, + { select: ':last-child(n)', expect: { throws: true } }, + { select: ':only-child(n)', expect: { throws: true } }, + { select: ':nth-child(2+0)', expect: { throws: true } }, + ], + }, + + { + name: 'id selectors', + markup: html, + markupMode: 'html-document', + cases: [ + { select: '#body', expect: { ids: ['body'] } }, + { select: 'body#body', expect: { ids: ['body'] } }, + { select: 'ul#first', expect: { ids: [] } }, + + { select: '#firstp #simon1', expect: { ids: ['simon1'] } }, + { select: '#firstp #foobar', expect: { ids: [] } }, + + { select: '#台北Táiběi', expect: { ids: ['台北Táiběi'] } }, + { select: '#台北Táiběi, #台北', expect: { ids: ['台北Táiběi', '台北'] } }, + { select: 'div #台北', expect: { ids: ['台北'] } }, + { select: 'form > #台北', expect: { ids: ['台北'] } }, + + { select: '#foo\\:bar', expect: { ids: ['foo:bar'] } }, + { select: '#test\\.foo\\[5\\]bar', expect: { ids: ['test.foo[5]bar'] } }, + { select: 'div #foo\\:bar', expect: { ids: ['foo:bar'] } }, + { select: 'div #test\\.foo\\[5\\]bar', expect: { ids: ['test.foo[5]bar'] } }, + { select: 'form > #foo\\:bar', expect: { ids: ['foo:bar'] } }, + { select: 'form > #test\\.foo\\[5\\]bar', expect: { ids: ['test.foo[5]bar'] } }, + + { select: '#form > #radio1', expect: { ids: ['radio1'] } }, // bug #267 + { select: '#form #first', expect: { ids: [] } }, + { select: '#form > #option1a', expect: { ids: [] } }, + + { select: '#foo > *', expect: { ids: ['sndp', 'en', 'sap'] } }, + { select: '#firstUL > *', expect: { ids: [] } }, + + { select: '#lengthtest', expect: { ids: ['lengthtest'] } }, + { select: '#tName2', expect: { ids: [] } }, + { select: '#asdfasdf #foobar', expect: { ids: [] } }, // bug #986 + + { select: 'body div#form', expect: { ids: [] } }, + + { select: '#types_all', expect: { ids: ['types_all'] } }, + { select: '#fx-queue', expect: { ids: ['fx-queue'] } }, + { select: '#name\\+value', expect: { ids: ['name+value'] } }, + ], + }, + { + name: 'id selectors after document fragment append', + markup: html, + markupMode: 'html-document', + setupPage: async (page) => { + await page.evaluate(() => { + const main = document.getElementById('main'); + if (!main) throw new Error('#main not found'); + + const orphan = document.createElement('div'); + orphan.innerHTML = + 'tName1 A' + + 'tName2 A' + + '
    tName1 Div
    '; + + const fragment = document.createDocumentFragment(); + while (orphan.firstChild) { + fragment.appendChild(orphan.firstChild); + } + + main.appendChild(fragment); + }); + }, + cases: [ + { select: '#tName1', expect: { ids: ['tName1'] } }, + { select: '#tName2', expect: { ids: [] } }, + ], + }, + + { + name: 'class selectors', + markup: html, + markupMode: 'html-document', + cases: [ + { select: '.blog', expect: { ids: ['mark', 'simon'] } }, + { select: '.GROUPS', expect: { ids: ['groups'] } }, + { select: '.blog.link', expect: { ids: ['simon'] } }, + { select: 'a.blog', expect: { ids: ['mark', 'simon'] } }, + { select: 'p .blog', expect: { ids: ['mark', 'simon'] } }, + + { select: 'p .blog', expect: { ids: ['mark', 'simon'] } }, + + { select: '.台北Táiběi', expect: { ids: ['utf8class1'] } }, + { select: '.台北', expect: { ids: ['utf8class1', 'utf8class2'] } }, + { select: '.台北Táiběi.台北', expect: { ids: ['utf8class1'] } }, + { select: '.台北Táiběi, .台北', expect: { ids: ['utf8class1', 'utf8class2'] } }, + { select: 'div .台北Táiběi', expect: { ids: ['utf8class1'] } }, + { select: 'form > .台北Táiběi', expect: { ids: ['utf8class1'] } }, + + { select: '.foo\\:bar', expect: { ids: ['foo:bar'] } }, + { select: '.test\\.foo\\[5\\]bar', expect: { ids: ['test.foo[5]bar'] } }, + { select: 'div .foo\\:bar', expect: { ids: ['foo:bar'] } }, + { select: 'div .test\\.foo\\[5\\]bar', expect: { ids: ['test.foo[5]bar'] } }, + { select: 'form > .foo\\:bar', expect: { ids: ['foo:bar'] } }, + { select: 'form > .test\\.foo\\[5\\]bar', expect: { ids: ['test.foo[5]bar'] } }, + ], + }, + + { + name: 'class selectors in detached subtree', + markup: '', + cases: [], + setupPage: async (page) => { + const result = await page.evaluate(() => { + const div = document.createElement('div'); + div.innerHTML = "
    "; + + const first = NW.Dom.select('.e', div).map(el => el.getAttribute('id')); + div.lastChild && ((div.lastChild as Element).className = 'e'); + const second = NW.Dom.select('.e', div).map(el => el.getAttribute('id')); + + return { first, second }; + }); + + expect(result.first).toEqual(['first']); + expect(result.second).toEqual(['first', 'second']); + }, + }, + + { + name: 'name selectors', + markup: html, + markupMode: 'html-document', + setupPage: async (page) => { + await page.evaluate(() => { + const main = document.getElementById('main'); + if (!main) throw new Error('#main not found'); + + const orphan = document.createElement('div'); + orphan.innerHTML = + 'tName1 A' + + 'tName2 A' + + '
    tName1 Div
    '; + + const fragment = document.createDocumentFragment(); + while (orphan.firstChild) { + fragment.appendChild(orphan.firstChild); + } + + main.appendChild(fragment); + }); + }, + cases: [ + { select: 'input[name=action]', expect: { ids: ['text1'] } }, + { select: "input[name='action']", expect: { ids: ['text1'] } }, + { select: 'input[name="action"]', expect: { ids: ['text1'] } }, + + { select: '[name=test]', expect: { ids: ['length', 'fx-queue'] } }, + { select: '[name=div]', expect: { ids: ['fadein'] } }, + { select: '*[name=iframe]', expect: { ids: ['iframe'] } }, + + { select: "input[name='types[]']", expect: { ids: ['types_all', 'types_anime', 'types_movie'] } }, + + { select: '#form input[name=action]', expect: { ids: ['text1'] } }, + { select: "#form input[name='foo[bar]']", expect: { ids: ['hidden2'] } }, + { select: "#form[action='formaction']", expect: { ids: ['form'] } }, + + { select: '[name=tName1]', expect: { ids: ['tName1ID'] } }, + { select: '[name=tName2]', expect: { ids: ['tName2ID'] } }, + ], + }, + + { + name: 'multiple selectors', + markup: html, + markupMode: 'html-document', + cases: [ + { select: 'h2, p', expect: { ids: ['banner', 'userAgent', 'firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'h2 , p', expect: { ids: ['banner', 'userAgent', 'firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'h2 , p', expect: { ids: ['banner', 'userAgent', 'firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'h2,p', expect: { ids: ['banner', 'userAgent', 'firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + + { select: 'a.blog, p', expect: { ids: ['firstp', 'ap', 'mark', 'sndp', 'en', 'sap', 'simon', 'first'] } }, + { select: 'a.blog , p', expect: { ids: ['firstp', 'ap', 'mark', 'sndp', 'en', 'sap', 'simon', 'first'] } }, + { select: 'a.blog ,p', expect: { ids: ['firstp', 'ap', 'mark', 'sndp', 'en', 'sap', 'simon', 'first'] } }, + { select: 'a.blog,p', expect: { ids: ['firstp', 'ap', 'mark', 'sndp', 'en', 'sap', 'simon', 'first'] } }, + ], + }, + + { + name: 'child and adjacent selectors', + markup: html, + markupMode: 'html-document', + cases: [ + { select: 'p > a', expect: { ids: ['simon1', 'google', 'groups', 'mark', 'yahoo', 'simon'] } }, + { select: 'p> a', expect: { ids: ['simon1', 'google', 'groups', 'mark', 'yahoo', 'simon'] } }, + { select: 'p >a', expect: { ids: ['simon1', 'google', 'groups', 'mark', 'yahoo', 'simon'] } }, + { select: 'p>a', expect: { ids: ['simon1', 'google', 'groups', 'mark', 'yahoo', 'simon'] } }, + + { select: 'p > a.blog', expect: { ids: ['mark', 'simon'] } }, + { select: 'code > *', expect: { ids: ['anchor1', 'anchor2'] } }, + { select: 'p > * > *', expect: { ids: ['anchor1', 'anchor2'] } }, + + { select: 'a + a', expect: { ids: ['groups'] } }, + { select: 'a +a', expect: { ids: ['groups'] } }, + { select: 'a+ a', expect: { ids: ['groups'] } }, + { select: 'a+a', expect: { ids: ['groups'] } }, + + { select: 'p + p', expect: { ids: ['ap', 'en', 'sap'] } }, + { select: 'p#firstp + p', expect: { ids: ['ap'] } }, + { select: 'p[lang=en] + p', expect: { ids: ['sap'] } }, + { select: 'a.GROUPS + code + a', expect: { ids: ['mark'] } }, + + { select: 'a + a, code > a', expect: { ids: ['groups', 'anchor1', 'anchor2'] } }, + + { select: 'div.blah > p > a', expect: { ids: [] } }, + { select: 'div.foo > span > a', expect: { ids: [] } }, + { select: '.container div:not(.excluded) div', expect: { ids: [] } }, + + { select: '* > :first-child', ref: { by: 'id', id: 'nothiddendiv' }, expect: { ids: ['nothiddendivchild'] } }, + { select: '* > :nth-child(1)', ref: { by: 'id', id: 'nothiddendiv' }, expect: { ids: ['nothiddendivchild'] } }, + { select: '* > *:first-child', ref: { by: 'id', id: 'nothiddendiv' }, expect: { ids: ['nothiddendivchild'] } }, + + { select: '.fototab > .thumbnails > a', expect: { ids: [] } }, + + { select: 'p:first-child', expect: { ids: ['firstp', 'sndp'] } }, + { select: 'p:nth-child(1)', expect: { ids: ['firstp', 'sndp'] } }, + { select: 'p:not(:nth-child(1))', expect: { ids: ['ap', 'en', 'sap', 'first'] } }, + ], + }, + + { + name: 'first-child cache invalidation', + markup: html, + markupMode: 'html-document', + setupPage: async (page) => { + await page.evaluate(() => { + const div = document.createElement('div'); + let divs = NW.Dom.select('p:first-child', null, null); + + for (let i = 0; i < divs.length; i++) { + divs[i].parentNode?.insertBefore(div.cloneNode(false), divs[i].nextSibling); + } + + divs = NW.Dom.select('p:first-child', null, null); + + for (let i = 0; i < divs.length; i++) { + const inserted = divs[i].parentNode?.insertBefore(div.cloneNode(false), divs[i]); + const p = inserted?.nextSibling; + p?.parentNode?.removeChild(p); + } + }); + }, + cases: [ + { select: 'p:first-child', expect: { ids: [] } }, + ], + }, + + { + name: 'last-child and nth-child selectors', + markup: html, + markupMode: 'html-document', + cases: [ + { select: 'p:last-child', expect: { ids: ['sap'] } }, + { select: 'a:last-child', expect: { ids: ['simon1', 'anchor1', 'mark', 'yahoo', 'anchor2', 'simon', 'liveLink1', 'liveLink2'] } }, + + { select: '#main form#form > *:nth-child(2)', expect: { ids: ['text1'] } }, + { select: '#main form#form > :nth-child(2)', expect: { ids: ['text1'] } }, + + // changed `select:first` to `select:first-of-type`; `:first` is jQuery-only + { select: '#form select:first-of-type option:nth-child(3)', expect: { ids: ['option1c'] } }, + { select: '#form select:first-of-type option:nth-child(0n+3)', expect: { ids: ['option1c'] } }, + { select: '#form select:first-of-type option:nth-child(1n+0)', expect: { ids: ['option1a', 'option1b', 'option1c', 'option1d'] } }, + { select: '#form select:first-of-type option:nth-child(1n)', expect: { ids: ['option1a', 'option1b', 'option1c', 'option1d'] } }, + { select: '#form select:first-of-type option:nth-child(n)', expect: { ids: ['option1a', 'option1b', 'option1c', 'option1d'] } }, + { select: '#form select:first-of-type option:nth-child(even)', expect: { ids: ['option1b', 'option1d'] } }, + { select: '#form select:first-of-type option:nth-child(odd)', expect: { ids: ['option1a', 'option1c'] } }, + { select: '#form select:first-of-type option:nth-child(2n)', expect: { ids: ['option1b', 'option1d'] } }, + { select: '#form select:first-of-type option:nth-child(2n+1)', expect: { ids: ['option1a', 'option1c'] } }, + { select: '#form select:first-of-type option:nth-child(3n)', expect: { ids: ['option1c'] } }, + { select: '#form select:first-of-type option:nth-child(3n+1)', expect: { ids: ['option1a', 'option1d'] } }, + { select: '#form select:first-of-type option:nth-child(3n+2)', expect: { ids: ['option1b'] } }, + { select: '#form select:first-of-type option:nth-child(3n+3)', expect: { ids: ['option1c'] } }, + { select: '#form select:first-of-type option:nth-child(3n-1)', expect: { ids: ['option1b'] } }, + { select: '#form select:first-of-type option:nth-child(3n-2)', expect: { ids: ['option1a', 'option1d'] } }, + { select: '#form select:first-of-type option:nth-child(3n-3)', expect: { ids: ['option1c'] } }, + { select: '#form select:first-of-type option:nth-child(3n+0)', expect: { ids: ['option1c'] } }, + { select: '#form select:first-of-type option:nth-child(-n+3)', expect: { ids: ['option1a', 'option1b', 'option1c'] } }, + + { select: '#form #select1 option:nth-child( 3n - 3)', expect: { ids: ['option1c'] } }, + { select: '#form #select1 option:nth-child(3n - 3 )', expect: { ids: ['option1c'] } }, + { select: '#form #select1 option:nth-child(\t 3n - 3)', expect: { ids: ['option1c'] } }, + { select: '#form #select1 option:nth-child(3n - 3 \t)', expect: { ids: ['option1c'] } }, + { select: '#form #select1 option:nth-child( \t 3n - 3)', expect: { ids: ['option1c'] } }, + { select: '#form #select1 option:nth-child(3n - 3 \t )', expect: { ids: ['option1c'] } }, + { select: '#form #select1 option:nth-child( \t\t\t 3n - 3)', expect: { ids: ['option1c'] } }, + { select: '#form #select1 option:nth-child(3n - 3 \t\t\t )', expect: { ids: ['option1c'] } }, + ], + }, + + { + name: 'attribute selectors', + markup: html, + markupMode: 'html-document', + setupPage: async (page) => { + await page.evaluate(() => { + const anchor2 = document.getElementById('anchor2') as HTMLAnchorElement | null; + if (anchor2) anchor2.href = '#2'; + + const inputs = NW.Dom.select('form input'); + if (inputs[0]) (inputs[0] as HTMLInputElement & { test?: number }).test = 0; + if (inputs[1]) (inputs[1] as HTMLInputElement & { test?: number }).test = 1; + }); + }, + cases: [ + { select: 'a[title]', expect: { ids: ['google'] } }, + { select: '*[title]', expect: { ids: ['google'] } }, + { select: '[title]', expect: { ids: ['google'] } }, + { select: 'a[ title ]', expect: { ids: ['google'] } }, + + { select: "a[rel='bookmark']", expect: { ids: ['simon1'] } }, + { select: 'a[rel="bookmark"]', expect: { ids: ['simon1'] } }, + { select: 'a[rel=bookmark]', expect: { ids: ['simon1'] } }, + { select: "a[href='http://www.google.com/']", expect: { ids: ['google'] } }, + { select: "a[ rel = 'bookmark' ]", expect: { ids: ['simon1'] } }, + + { select: "p a[href^='#']", expect: { ids: ['anchor2'] } }, + { select: 'p a[href*="#"]', expect: { ids: ['simon1', 'anchor2'] } }, + + { select: 'form label[for]', expect: { ids: ['label-for'] } }, + { select: '#form [for=action]', expect: { ids: ['label-for'] } }, + + // Disabled tests - expandos don't work in browsers + // { select: 'form input[test]', expect: { ids: ['text1', 'text2'] } }, + // { select: 'form input[test=0]', expect: { ids: ['text1'] } }, + // { select: 'form input[test=1]', expect: { ids: ['text2'] } }, + + { select: "input[name^='foo[']", expect: { ids: ['hidden2'] } }, + { select: "input[name^='foo[bar]']", expect: { ids: ['hidden2'] } }, + { select: "input[name*='[bar]']", expect: { ids: ['hidden2'] } }, + { select: "input[name$='bar]']", expect: { ids: ['hidden2'] } }, + { select: "input[name$='[bar]']", expect: { ids: ['hidden2'] } }, + { select: "input[name$='foo[bar]']", expect: { ids: ['hidden2'] } }, + { select: "input[name*='foo[bar]']", expect: { ids: ['hidden2'] } }, + + { select: "#form input[type='radio'], #form input[type='hidden']", expect: { ids: ['radio1', 'radio2', 'hidden1'] } }, + { select: '#form input[type=\'radio\'], #form input[type="hidden"]', expect: { ids: ['radio1', 'radio2', 'hidden1'] } }, + { select: "#form input[type='radio'], #form input[type=hidden]", expect: { ids: ['radio1', 'radio2', 'hidden1'] } }, + + { select: 'span[lang=中文]', expect: { ids: ['台北'] } }, + + { select: "a[href ^= 'http://www']", expect: { ids: ['google', 'yahoo'] } }, + { select: "a[href $= 'org/']", expect: { ids: ['mark'] } }, + { select: "a[href *= 'google']", expect: { ids: ['google', 'groups'] } }, + { select: "#ap a:not([hreflang='en'])", expect: { ids: ['google', 'groups', 'anchor1'] } }, + + { select: "#select1 option[value='']", expect: { ids: ['option1a'] } }, + { select: "#select1 option:not([value=''])", expect: { ids: ['option1b', 'option1c', 'option1d'] } }, + + { select: '#select1 option[selected]', expect: { ids: [] } }, + { select: '#select2 option[selected]', expect: { ids: ['option2d'] } }, + { select: '#select3 option[selected]', expect: { ids: ['option3b', 'option3c'] } }, + + { select: '#select1 option:checked', expect: { ids: ['option1a'] } }, + { select: '#select2 option:checked', expect: { ids: ['option2d'] } }, + { select: '#select3 option:checked', expect: { ids: ['option3b', 'option3c'] } }, + + { select: "input[name='foo[bar]']", expect: { ids: ['hidden2'] } }, + + { select: ':matches(#form select[multiple])', expect: { ids: ['select3'] }, status: 'fixme' }, + { select: ':matches(#form select[name=select1], #form select[name=select2])', expect: { ids: ['select1', 'select2'] }, status: 'fixme' }, + { select: ':matches(#form select[name=select1], #form select[name=select2])', expect: { ids: ['select1', 'select2'] }, status: 'fixme' }, + { select: ':matches(#form select[multiple], :-test-invalid)', expect: { throws: true }, status: 'fixme' }, + + { select: ':is(#form select[multiple])', expect: { ids: ['select3'] } }, + { select: ':is(#form select[name=select1], #form select[name=select2])', expect: { ids: ['select1', 'select2'] } }, + { select: ':is(#form select[name=select1], #form select[name=select2])', expect: { ids: ['select1', 'select2'] } }, + { select: ':is(#form select[multiple], :-test-invalid)', expect: { ids: ['select3'] }, status: 'fixme' }, + + { select: '#form select:not([multiple])', expect: { ids: ['select1', 'select2'] } }, + { select: '#form select:not([name=select1])', expect: { ids: ['select2', 'select3'] } }, + { select: "#form select:not([name='select1'])", expect: { ids: ['select2', 'select3'] } }, + ], + }, + + { + name: 'pseudo selectors 1', + markup: html, + markupMode: 'html-document', + cases: [ + { select: 'p:first-child', expect: { ids: ['firstp', 'sndp'] } }, + { select: 'p:last-child', expect: { ids: ['sap'] } }, + { select: 'a:only-child', expect: { ids: ['simon1', 'anchor1', 'yahoo', 'anchor2', 'liveLink1', 'liveLink2'] } }, + { select: 'ul:empty', expect: { ids: ['firstUL'] } }, + + { select: '#form input:not([type=hidden]):enabled', expect: { ids: ['text1', 'radio1', 'radio2', 'check1', 'check2', 'hidden2', 'name', 'search'] } }, + { select: '#form input:disabled', expect: { ids: ['text2'] } }, + { select: '#form input:checked', expect: { ids: ['radio2', 'check1'] } }, + + { select: '#form option:checked', expect: { ids: ['option1a', 'option2d', 'option3b', 'option3c'] } }, + + // jQuery-only text pseudos; not valid in the native-parity harness + // { select: "a:contains('Google')", expect: { ids: ['google', 'groups'] } }, + // { select: "a:contains('Google Groups')", expect: { ids: ['groups'] } }, + // { select: "a:contains('Google Groups (Link)')", expect: { ids: ['groups'] } }, + // { select: "a:contains('(Link)')", expect: { ids: ['groups'] } }, + + { select: 'p ~ div', expect: { ids: ['foo', 'moretests', 'tabindex-tests', 'liveHandlerOrder'] } }, + { select: 'a.blog:not(.link)', expect: { ids: ['mark'] } }, + // { select: "#form option:not(:contains('Nothing'),#option1b,:checked)", expect: { ids: ['option1c', 'option1d', 'option2b', 'option2c', 'option3d', 'option3e'] } }, + { select: "#form option:not([id^='opt']:nth-child(-n+3))", expect: { ids: ['option1d', 'option2d', 'option3d', 'option3e'] } }, + { select: "#form option:not(:not(:checked))[id^='option3']", expect: { ids: ['option3b', 'option3c'] } }, + { select: 'p:not(.foo)', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + + // invalid compound selector inside :not() pseudo-class + { select: 'p:not(div.foo)', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'p:not(p.foo)', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'p:not(div)', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'p:not(.foo)', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'p:not(#blargh)', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'p:not(div):not(.foo)', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + + // invalid compound selector inside :not() pseudo-class + { select: 'p:not(div):not(#blargh)', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'p:not(p):not(#blargh)', expect: { ids: [] } }, + { select: 'p:not(div#blargh)', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'p:not(p#blargh)', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'p:not(div)', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'p:not(#blargh)', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + + { select: 'p:not(a)', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'p:not(a, b)', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'p:not(a, b, div)', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + { select: 'p:not(p)', expect: { ids: [] } }, + { select: 'p:not(a,p)', expect: { ids: [] } }, + { select: 'p:not(p,a)', expect: { ids: [] } }, + { select: 'p:not(a,p,b)', expect: { ids: [] } }, + // { select: ':input:not(:image,:input,:submit)', expect: { ids: [] } }, + + // jQuery-only positional pseudos; keep parked for now + // { select: 'p:nth(1)', expect: { ids: ['ap'] } }, + // { select: 'p:first', expect: { ids: ['firstp'] } }, + // { select: 'p:last', expect: { ids: ['first'] } }, + // { select: 'p:even', expect: { ids: ['firstp', 'sndp', 'sap'] } }, + // { select: 'p:odd', expect: { ids: ['ap', 'en', 'first'] } }, + // { select: 'p:eq(1)', expect: { ids: ['ap'] } }, + // { select: 'p:gt(0)', expect: { ids: ['ap', 'sndp', 'en', 'sap', 'first'] } }, + // { select: 'p:lt(3)', expect: { ids: ['firstp', 'ap', 'sndp'] } }, + // { select: 'p:parent', expect: { ids: ['firstp', 'ap', 'sndp', 'en', 'sap', 'first'] } }, + // { select: '#form input:visible', expect: { ids: [] } }, + // { select: 'div:visible:not(#testrunner-toolbar):lt(2)', expect: { ids: ['nothiddendiv', 'nothiddendivchild'] } }, + // { select: '#form input:hidden', expect: { ids: ['text1', 'text2', 'radio1', 'radio2', 'check1', 'check2', 'hidden1', 'hidden2', 'name', 'search'] } }, + // { select: '#main:hidden', expect: { ids: ['main'] } }, + // { select: '#dl:hidden', expect: { ids: ['dl'] } }, + ], + }, + + // Legacy jQuery visibility / position pseudo tests. + // Preserved from the original suite but not active in the native-parity harness, + { + name: 'jquery visibility and position pseudos (legacy)', + status: 'skip', + markup: html, + markupMode: 'html-document', + steps: [ + { + // 0x0 with zero font metrics + setupPage: async page => { await setElementProps(page, '#nothiddendivchild', { fontSize: '0', lineHeight: '0', width: '0', height: '0' }); }, + cases: [ + { select: '#nothiddendivchild:hidden', expect: { ids: ['nothiddendivchild'] } }, + { select: '#nothiddendivchild:visible', expect: { ids: [] } }, + ], + }, + { + // 1x0 with zero font metrics + setupPage: async page => { await setElementProps(page, '#nothiddendivchild', { fontSize: '0', lineHeight: '0', width: '1px', height: '0' }); }, + cases: [ + { select: '#nothiddendivchild:visible', expect: { ids: ['nothiddendivchild'] } }, + { select: '#nothiddendivchild:hidden', expect: { ids: [] } }, + ], + }, + { + // 0x1 with zero font metrics + setupPage: async page => { await setElementProps(page, '#nothiddendivchild', { fontSize: '0', lineHeight: '0', width: '0', height: '1px' }); }, + cases: [ + { select: '#nothiddendivchild:visible', expect: { ids: ['nothiddendivchild'] } }, + { select: '#nothiddendivchild:hidden', expect: { ids: [] } }, + ], + }, + { + // 1x1 with zero font metrics + setupPage: async page => { await setElementProps(page, '#nothiddendivchild', { fontSize: '0', lineHeight: '0', width: '1px', height: '1px' }); }, + cases: [ + { select: '#nothiddendivchild:visible', expect: { ids: ['nothiddendivchild'] } }, + { select: '#nothiddendivchild:hidden', expect: { ids: [] } }, + ], + }, + { + setupPage: async page => { await setElementProps(page, '#nothiddendivchild', { width: '', height: '', fontSize: '', lineHeight: '' }); }, + cases: [ + { select: 'div#nothiddendiv:eq(0)', expect: { ids: ['nothiddendiv'] } }, + { select: 'div#nothiddendiv:last', expect: { ids: ['nothiddendiv'] } }, + { select: 'div#nothiddendiv:not(:gt(0))', expect: { ids: ['nothiddendiv'] } }, + { select: '#foo > :not(:first)', expect: { ids: ['en', 'sap'] } }, + { select: 'select > :not(:gt(2))', expect: { ids: ['option1a', 'option1b', 'option1c'] } }, + { select: 'select:lt(2) :not(:first)', expect: { ids: ['option1b', 'option1c', 'option1d', 'option2a', 'option2b', 'option2c', 'option2d'] } }, + { select: 'div.nothiddendiv:eq(0)', expect: { ids: ['nothiddendiv'] } }, + { select: 'div.nothiddendiv:last', expect: { ids: ['nothiddendiv'] } }, + { select: 'div.nothiddendiv:not(:lt(0))', expect: { ids: ['nothiddendiv'] } }, + + { select: 'div div:eq(0)', expect: { ids: ['nothiddendivchild'] } }, + { select: 'div div:eq(5)', expect: { ids: ['t2037'] } }, + { select: 'div div:eq(27)', expect: { ids: ['hide'] } }, + { select: 'div div:first', expect: { ids: ['nothiddendivchild'] } }, + { select: 'div > div:first', expect: { ids: ['nothiddendivchild'] } }, + { select: '#dl div:first div:first', expect: { ids: ['foo'] } }, + { select: '#dl div:first > div:first', expect: { ids: ['foo'] } }, + { select: 'div#nothiddendiv:first > div:first', expect: { ids: ['nothiddendivchild'] } }, + ], + } + ], + }, + + { + name: 'form and header pseudo selectors', + status: 'skip', // form pseudo selectors are jQuery-only; + markup: html, + markupMode: 'html-document', + cases: [ + { select: '#form :input', expect: { ids: ['text1', 'text2', 'radio1', 'radio2', 'check1', 'check2', 'hidden1', 'hidden2', 'name', 'search', 'button', 'area1', 'select1', 'select2', 'select3'] } }, + { select: '#form :radio', expect: { ids: ['radio1', 'radio2'] } }, + { select: '#form :checkbox', expect: { ids: ['check1', 'check2'] } }, + { select: '#form :text:not(#search)', expect: { ids: ['text1', 'text2', 'hidden2', 'name'] } }, + { select: '#form :radio:checked', expect: { ids: ['radio2'] } }, + { select: '#form :checkbox:checked', expect: { ids: ['check1'] } }, + { select: '#form :radio:checked, #form :checkbox:checked', expect: { ids: ['radio2', 'check1'] } }, + + { select: ':header', expect: { ids: ['header', 'banner', 'userAgent'] } }, + ], + }, + + { + name: ':has() selector', + markup: html, + markupMode: 'html-document', + cases: [ + { select: 'p:has(a)', expect: { ids: ['firstp', 'ap', 'en', 'sap'] } }, + ], + }, + + { + name: 'escaped attribute selector values', + markup: ` +
    +
    hi there
    + +
    foo
    +
    foo
    +
    foo
    +
    foo
    +
    foo
    +
    foo
    +
    foo
    +
    foo
    +
    + `, + cases: [ + { select: `[data-test="foo]bar"]`, expect: { ids: ['escapedSelectorClosingBracket'] } }, + { select: `[data-test="foo\\"bar"]`, expect: { ids: ['escapedSelectorDoubleQuote'] } }, + { select: `[data-test='foo\\'bar']`, expect: { ids: ['escapedSelectorSingleQuote'] } }, + { select: `[data-test='foo\\\\bar']`, expect: { ids: ['escapedSelectorBackslash'] } }, + { select: `[data-test='foo\\a bar']`, expect: { ids: ['escapedSelectorLF'] } }, + { select: `[data-test='foo\\00000d bar']`, expect: { ids: ['escapedSelectorCR'] } }, + { select: `[data-test='foo\\24B62 bar']`, expect: { ids: ['escapedSupplementary'] } }, + { select: `[data-test='foo\\\\\\"\\'\\62 ar']`, expect: { ids: ['escapedCombined'] } }, + + { select: `[data-test=foo\\]bar]`, expect: { ids: ['escapedSelectorClosingBracket'] } }, + { select: `[data-test=foo\\"bar]`, expect: { ids: ['escapedSelectorDoubleQuote'] } }, + { select: `[data-test=foo\\'bar]`, expect: { ids: ['escapedSelectorSingleQuote'] } }, + { select: `[data-test=foo\\\\bar]`, expect: { ids: ['escapedSelectorBackslash'] } }, + { select: `[data-test=foo\\a bar]`, expect: { ids: ['escapedSelectorLF'] } }, + { select: `[data-test=foo\\00000d bar]`, expect: { ids: ['escapedSelectorCR'] } }, + { select: `[data-test=foo\\24B62 bar]`, expect: { ids: ['escapedSupplementary'] } }, + { select: `[data-test=foo\\\\\\"\\'\\62 ar]`, expect: { ids: ['escapedCombined'] } }, + ], + } + +]); + +const setElementProps = async ( + page: Page, + selector: string, + props: Partial> +) => { + await page.evaluate(({ selector, props }) => { + const el = NW.Dom.first(selector) as HTMLElement | null; + if (!el) throw new Error(`${selector} not found`); + if (props.width !== undefined) el.style.width = props.width; + if (props.height !== undefined) el.style.height = props.height; + if (props.fontSize !== undefined) el.style.fontSize = props.fontSize; + if (props.lineHeight !== undefined) el.style.lineHeight = props.lineHeight; + }, { selector, props }); +}; \ No newline at end of file diff --git a/test_new/browser/jsvm.test.ts b/test_new/browser/jsvm.test.ts new file mode 100644 index 0000000..fc938a8 --- /dev/null +++ b/test_new/browser/jsvm.test.ts @@ -0,0 +1,27 @@ +import { runScenarios } from "./harness/scenarios"; + +runScenarios('jsvm', 'normal', [ + { + name: 'load test selectors', + markup: ` +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + `, + cases: [ + { select: '#test1 div:not(:empty)', expect: { count: 4 } }, + { select: '#test1 div:nth-child(even):empty', expect: { count: 2 } }, + ], + }, +]); \ No newline at end of file diff --git a/test_new/browser/prototype.test.ts b/test_new/browser/prototype.test.ts new file mode 100644 index 0000000..b808764 --- /dev/null +++ b/test_new/browser/prototype.test.ts @@ -0,0 +1,509 @@ +import { runScenarios } from "./harness/scenarios"; +import { expect } from "@playwright/test"; + +runScenarios('prototype 1', 'normal', [ + { + name: 'selector engine basics', + markup: ` +
    +
    +
    +
    `, + cases: [ + { select: '.test_class', expect: { count: 2, ids: ['test_div_parent', 'test_div_child'] } }, + { + select: '.test_class', + ref: { by: 'id', id: 'test_div_parent' }, + expect: { count: 1, ids: ['test_div_child'] } + }, + { select: '.non_existent', expect: { count: 0, ids: [] } }, + ], + }, +]); + +const nwsapiProtoTestHtml = ` + + + + Unit test file | Selector | default template | 2010-03-04 16:13 + + + + + + + + + + + +
    + + + + + + +`; + +runScenarios('prototype 2', 'normal', [ + { + name: 'standard prototype selectors', + markup: nwsapiProtoTestHtml, + markupMode: 'html-document', + cases: [ + // testSelectorWithTagName + { select: 'li' }, + { select: 'strong', expect: { ids: ['strong'] } }, + { select: 'nonexistent', expect: { count: 0, ids: [] } }, + { select: '*' }, + + // testSelectorWithId + { select: '#fixtures', expect: { ids: ['fixtures'] } }, + { select: '#nonexistent', expect: { count: 0, ids: [] } }, + { select: '#troubleForm', expect: { ids: ['troubleForm'] } }, + + // testSelectorWithClassName + { select: '.first', expect: { ids: ['p', 'link_1', 'item_1'] } }, + { select: '.second', expect: { count: 0, ids: [] } }, + + // testSelectorWithTagNameAndId + { select: 'strong#strong', expect: { ids: ['strong'] } }, + { select: 'p#strong', expect: { count: 0, ids: [] } }, + + // testSelectorWithTagNameAndClassName + { select: 'a.internal', expect: { ids: ['link_1', 'link_2'] } }, + { select: 'a.internal.highlight', expect: { ids: ['link_2'] } }, + { select: 'a.highlight.internal', expect: { ids: ['link_2'] } }, + { select: 'a.highlight.internal.nonexistent', expect: { count: 0, ids: [] } }, + + // testSelectorWithIdAndClassName + { select: '#link_2.internal', expect: { ids: ['link_2'] } }, + { select: '.internal#link_2', expect: { ids: ['link_2'] } }, + { select: '#link_2.internal.highlight', expect: { ids: ['link_2'] } }, + { select: '#link_2.internal.nonexistent', expect: { count: 0, ids: [] } }, + + // testSelectorWithTagNameAndIdAndClassName + { select: 'a#link_2.internal', expect: { ids: ['link_2'] } }, + { select: 'a.internal#link_2', expect: { ids: ['link_2'] } }, + { select: 'li#item_1.first', expect: { ids: ['item_1'] } }, + { select: 'li#item_1.nonexistent', expect: { count: 0, ids: [] } }, + { select: 'li#item_1.first.nonexistent', expect: { count: 0, ids: [] } }, + + // test$$MatchesAncestryWithTokensSeparatedByWhitespace + { select: '#fixtures a *', expect: { ids: ['em2', 'em', 'span'] } }, + { select: 'div#fixtures p', expect: { ids: ['p'] } }, + + // test$$CombinesResultsWhenMultipleExpressionsArePassed + { select: '#p a, ul#list li', expect: { ids: ['link_1', 'link_2', 'item_1', 'item_2', 'item_3'] } }, + + // testSelectorWithTagNameAndAttributeExistence + { select: 'h1[class]', expect: { equivalentCase: { select: '#fixtures h1' } } }, + { select: 'h1[CLASS]', expect: { equivalentCase: { select: '#fixtures h1' } } }, + { select: 'li#item_3[class]', expect: { ids: ['item_3'] } }, + + // testSelectorWithTagNameAndSpecificAttributeValue + { select: 'a[href="#"]', expect: { ids: ['link_1', 'link_2', 'link_3'] } }, + { select: "a[href='#']", expect: { ids: ['link_1', 'link_2', 'link_3'] } }, + + // testSelectorWithTagNameAndWhitespaceTokenizedAttributeValue + { select: 'a[class~="internal"]', expect: { ids: ['link_1', 'link_2'] } }, + { select: 'a[class~=internal]', expect: { ids: ['link_1', 'link_2'] } }, + + // testSelectorWithAttributeAndNoTagName + { select: '[href]', ref: { by: 'first', selector: 'body' }, expect: { equivalentCase: { select: 'a[href]' } } }, + { select: '[class~=internal]', expect: { equivalentCase: { select: 'a[class~="internal"]' } } }, + { select: '[id]', expect: { equivalentCase: { select: '*[id]' } } }, + { select: '[type=radio]', expect: { ids: ['checked_radio', 'unchecked_radio'] } }, + { select: '[type=checkbox]', expect: { equivalentCase: { select: '*[type=checkbox]' } } }, + { select: '[title]', expect: { ids: ['with_title', 'commaParent'] } }, + { select: '#troubleForm [type=radio]', expect: { equivalentCase: { select: '#troubleForm *[type=radio]' } } }, + { select: '#troubleForm [type]', expect: { equivalentCase: { select: '#troubleForm *[type]' } } }, + + // testSelectorWithAttributeContainingDash + { select: '[foo-bar]', expect: { ids: ['attr_with_dash'] } }, // attribute with hyphen + + // testSelectorWithUniversalAndHyphenTokenizedAttributeValue + { select: '*[xml:lang|="es"]', expect: { ids: ['item_3'] }, status: 'fixme' }, + { select: '*[xml:lang|="ES"]', expect: { ids: ['item_3'] }, status: 'fixme' }, + + // testSelectorWithTagNameAndNegatedAttributeValue + { select: 'a:not([href="#"])', expect: { count: 0, ids: [] } }, + + // testSelectorWithBracketAttributeValue + { select: '#troubleForm2 input[name="brackets[5][]"]', expect: { ids: ['chk_1', 'chk_2'] } }, + { select: '#troubleForm2 input[name="brackets[5][]"]:checked', expect: { ids: ['chk_1'] } }, + { select: '#troubleForm2 input[name="brackets[5][]"][value="2"]', expect: { ids: ['chk_2'] } }, + { select: '#troubleForm2 input[name=brackets\\[5\\]\\[\\]]', expect: { equivalentCase: { select: '#troubleForm2 input[name="brackets[5][]"]' }, count: 2 } }, + + // test$$WithNestedAttributeSelectors + { select: 'div[style] p[id] strong', expect: { ids: ['strong'] } }, + + // testSelectorWithMultipleConditions + { select: 'a[class~=external][href="#"]', expect: { ids: ['link_3'] } }, + { select: 'a[class~=external]:not([href="#"])', expect: { count: 0, ids: [] } }, + + // derived from testSelectorMatchElements + { select: '#list li', expect: { ids: ['item_1', 'item_2', 'item_3'] } }, + { select: '#fixtures a.internal', expect: { ids: ['link_1', 'link_2'] } }, + { select: '#fixtures p.last', expect: { count: 0, ids: [] } }, + { select: '#fixtures .inexistant, #fixtures a.internal', expect: { ids: ['link_1', 'link_2'] } }, + + // derived from testSelectorFindElement + { select: '#list li', expect: { ids: ['item_1', 'item_2', 'item_3'] } }, + { select: '#list li#item_3', expect: { ids: ['item_3'] } }, + { select: '#list em', expect: { count: 0, ids: [] } }, + + // derived from testElementMatch + { select: 'span', expect: { includesIds: ['dupL1'] } }, + { select: 'span#dupL1', expect: { includesIds: ['dupL1'] } }, + { select: 'div > span', expect: { includesIds: ['dupL1'] } }, // child combinator + { select: '#dupContainer span', expect: { includesIds: ['dupL1'] } }, // descendant combinator + { select: '#dupL1', expect: { includesIds: ['dupL1'] } }, // ID only + { select: 'span.span_foo', expect: { includesIds: ['dupL1'] } }, // class name 1 + { select: 'span.span_bar', expect: { includesIds: ['dupL1'] } }, // class name 2 + { select: 'span:first-child', expect: { includesIds: ['dupL1'] } }, // first-child pseudoclass + + { select: 'span.span_wtf', expect: { excludesIds: ['dupL1'] } }, // bogus class name + { select: '#dupL2', expect: { excludesIds: ['dupL1'] } }, // different ID + { select: 'div', expect: { excludesIds: ['dupL1'] } }, // different tag name + { select: 'span span', expect: { excludesIds: ['dupL1'] } }, // different ancestry + { select: 'span > span', expect: { excludesIds: ['dupL1'] } }, // different parent + { select: 'span:nth-child(5)', expect: { excludesIds: ['dupL1'] } }, // different pseudoclass + + { select: 'a[rel^=external]', expect: { includesIds: ['link_1'], excludesIds: ['link_2'] } }, + { select: 'a[rel^="external"]', expect: { includesIds: ['link_1'] } }, + { select: "a[rel^='external']", expect: { includesIds: ['link_1'] } }, + + + // testElementMatch + { match: 'span', ref: { by: 'id', id: 'dupL1' }, expect: { ids: ['dupL1'] } }, + { match: 'span#dupL1', ref: { by: 'id', id: 'dupL1' }, expect: { ids: ['dupL1'] } }, + { match: 'div > span', ref: { by: 'id', id: 'dupL1' }, expect: { ids: ['dupL1'] } }, // child combinator + { match: '#dupContainer span', ref: { by: 'id', id: 'dupL1' }, expect: { ids: ['dupL1'] } }, // descendant combinator + { match: '#dupL1', ref: { by: 'id', id: 'dupL1' }, expect: { ids: ['dupL1'] } }, // ID only + { match: 'span.span_foo', ref: { by: 'id', id: 'dupL1' }, expect: { ids: ['dupL1'] } }, // class name 1 + { match: 'span.span_bar', ref: { by: 'id', id: 'dupL1' }, expect: { ids: ['dupL1'] } }, // class name 2 + { match: 'span:first-child', ref: { by: 'id', id: 'dupL1' }, expect: { ids: ['dupL1'] } }, // first-child pseudoclass + + { match: 'span.span_wtf', ref: { by: 'id', id: 'dupL1' }, expect: { ids: [] } }, // bogus class name + { match: '#dupL2', ref: { by: 'id', id: 'dupL1' }, expect: { ids: [] } }, // different ID + { match: 'div', ref: { by: 'id', id: 'dupL1' }, expect: { ids: [] } }, // different tag name + { match: 'span span', ref: { by: 'id', id: 'dupL1' }, expect: { ids: [] } }, // different ancestry + { match: 'span > span', ref: { by: 'id', id: 'dupL1' }, expect: { ids: [] } }, // different parent + { match: 'span:nth-child(5)', ref: { by: 'id', id: 'dupL1' }, expect: { ids: [] } }, // different pseudoclass + + { match: 'a[rel^=external]', ref: { by: 'id', id: 'link_2' }, expect: { ids: [] } }, + { match: 'a[rel^=external]', ref: { by: 'id', id: 'link_1' }, expect: { ids: ['link_1'] } }, + { match: 'a[rel^="external"]', ref: { by: 'id', id: 'link_1' }, expect: { ids: ['link_1'] } }, + { match: "a[rel^='external']", ref: { by: 'id', id: 'link_1' }, expect: { ids: ['link_1'] } }, + + // testSelectorWithSpaceInAttributeValue + { select: 'cite[title="hello world!"]', expect: { ids: ['with_title'] } }, + + // testSelectorWithNamespacedAttributes + { + select: '[xml:lang]', + status: 'fixme', + expect: { + count: 2, + includesIds: ['item_3'], + equivalentCase: { select: '*[xml:lang]' } + } + }, + + // testSelectorWithChild + { select: 'p.first > a', expect: { ids: ['link_1', 'link_2'] } }, + { select: 'div#grandfather > div', expect: { ids: ['father', 'uncle'] } }, + { select: '#level1>span', expect: { ids: ['level2_1', 'level2_2'] } }, + { select: '#level1 > span', expect: { ids: ['level2_1', 'level2_2'] } }, + { select: '#level2_1 > *', expect: { ids: ['level3_1', 'level3_2'] } }, + { select: 'div > #nonexistent', expect: { count: 0, ids: [] } }, + { select: '#level1 > span' }, + + // testSelectorWithAdjacence + { select: 'div.brothers + div.brothers', expect: { ids: ['uncle'] } }, + { select: 'div.brothers + div', expect: { ids: ['uncle'] } }, + { select: '#level2_1+span', expect: { ids: ['level2_2'] } }, + { select: '#level2_1 + span', expect: { ids: ['level2_2'] } }, + { select: '#level2_1 + *', expect: { ids: ['level2_2'] } }, + { select: '#level2_2 + span', expect: { count: 0, ids: [] } }, + { select: '#level3_1 + span', expect: { ids: ['level3_2'] } }, + { select: '#level3_1 + *', expect: { ids: ['level3_2'] } }, + { select: '#level3_2 + *', expect: { count: 0, ids: [] } }, + { select: '#level3_1 + em', expect: { count: 0, ids: [] } }, + + // testSelectorWithLaterSibling + { select: 'h1 ~ ul', expect: { ids: ['list'] } }, + { select: '#level2_1 ~ span', expect: { ids: ['level2_2'] } }, + { select: '#level2_1 ~ *', expect: { ids: ['level2_2', 'level2_3'] } }, + { select: '#level2_2 ~ span', expect: { count: 0, ids: [] } }, + { select: '#level3_2 ~ *', expect: { count: 0, ids: [] } }, + { select: '#level3_1 ~ em', expect: { count: 0, ids: [] } }, + { select: '#level3_1 ~ #level3_2', expect: { ids: ['level3_2'] } }, + { select: 'span ~ #level3_2', expect: { ids: ['level3_2'] } }, + { select: 'div ~ #level3_2', expect: { count: 0, ids: [] } }, + { select: 'div ~ #level2_3', expect: { count: 0, ids: [] } }, + + // testSelectorWithNewAttributeOperators + { select: 'div[class^=bro]', expect: { ids: ['father', 'uncle'] } }, // matching beginning of string + { select: 'div[class$=men]', expect: { ids: ['father', 'uncle'] } }, // matching end of string + { select: 'div[class*="ers m"]', expect: { ids: ['father', 'uncle'] } }, // matching substring + { select: '#level1 *[id^="level2_"]', expect: { ids: ['level2_1', 'level2_2', 'level2_3'] } }, + { select: '#level1 *[id^=level2_]', expect: { ids: ['level2_1', 'level2_2', 'level2_3'] } }, + { select: '#level1 *[id$="_1"]', expect: { ids: ['level2_1', 'level3_1'] } }, + { select: '#level1 *[id$=_1]', expect: { ids: ['level2_1', 'level3_1'] } }, + { select: '#level1 *[id*="2"]', expect: { ids: ['level2_1', 'level3_2', 'level2_2', 'level2_3'] } }, + { select: "#level1 *[id*='2']", expect: { ids: ['level2_1', 'level3_2', 'level2_2', 'level2_3'] } }, + + // benchmark(function() { $$('#level1 *[id^=level2_]') }, 1000, '[^=]') + { select: '#level1 *[id^=level2_]', expect: { ids: ['level2_1', 'level2_2', 'level2_3'] } }, + // benchmark(function() { $$('#level1 *[id$=_1]') }, 1000, '[$=]') + { select: '#level1 *[id$=_1]', expect: { ids: ['level2_1', 'level3_1'] } }, + // benchmark(function() { $$('#level1 *[id*=_2]') }, 1000, '[*=]') + { select: '#level1 *[id*=_2]', expect: { ids: ['level3_2', 'level2_2'] } }, + + // testSelectorWithDuplicates + { select: 'div div' }, + { select: '#dupContainer span span', expect: { ids: ['dupL2', 'dupL3', 'dupL4', 'dupL5'] } }, + + // benchmark(function() { $$('#dupContainer span span') }, 1000) + { select: '#dupContainer span span', expect: { ids: ['dupL2', 'dupL3', 'dupL4', 'dupL5'] } }, + + // testSelectorWithFirstLastOnlyNthNthLastChild + { select: '#level1>*:first-child', expect: { ids: ['level2_1'] } }, + { select: '#level1 *:first-child', expect: { ids: ['level2_1', 'level3_1', 'level_only_child'] } }, + { select: '#level1>*:last-child', expect: { ids: ['level2_3'] } }, + { select: '#level1 *:last-child', expect: { ids: ['level3_2', 'level_only_child', 'level2_3'] } }, + { select: '#level1>div:last-child', expect: { ids: ['level2_3'] } }, + { select: '#level1 div:last-child', expect: { ids: ['level2_3'] } }, + { select: '#level1>div:first-child', expect: { count: 0, ids: [] } }, + { select: '#level1>span:last-child', expect: { count: 0, ids: [] } }, + { select: '#level1 span:first-child', expect: { ids: ['level2_1', 'level3_1'] } }, + { select: '#level1:first-child', expect: { count: 0, ids: [] } }, + { select: '#level1>*:only-child', expect: { count: 0, ids: [] } }, + { select: '#level1 *:only-child', expect: { ids: ['level_only_child'] } }, + { select: '#level1:only-child', expect: { count: 0, ids: [] } }, + { select: '#p *:nth-last-child(2)', expect: { ids: ['link_2'] } }, // nth-last-child + { select: '#p *:nth-child(3)', expect: { ids: ['link_2'] } }, // nth-child + { select: '#p a:nth-child(3)', expect: { ids: ['link_2'] } }, // nth-child + { select: '#list > li:nth-child(n+2)', expect: { ids: ['item_2', 'item_3'] } }, + { select: '#list > li:nth-child(-n+2)', expect: { ids: ['item_1', 'item_2'] } }, + + // benchmark(function() { $$('#level1 *:first-child') }, 1000, ':first-child') + { select: '#level1 *:first-child', expect: { ids: ['level2_1', 'level3_1', 'level_only_child'] } }, + // benchmark(function() { $$('#level1 *:last-child') }, 1000, ':last-child') + { select: '#level1 *:last-child', expect: { ids: ['level3_2', 'level_only_child', 'level2_3'] } }, + // benchmark(function() { $$('#level1 *:only-child') }, 1000, ':only-child') + { select: '#level1 *:only-child', expect: { ids: ['level_only_child'] } }, + + // testSelectorWithFirstLastNthNthLastOfType + { select: '#p a:nth-of-type(2)', expect: { ids: ['link_2'] } }, // nth-of-type + { select: '#p a:nth-of-type(1)', expect: { ids: ['link_1'] } }, // nth-of-type + { select: '#p a:nth-last-of-type(1)', expect: { ids: ['link_2'] } }, // nth-last-of-type + { select: '#p a:first-of-type', expect: { ids: ['link_1'] } }, // first-of-type + { select: '#p a:last-of-type', expect: { ids: ['link_2'] } }, // last-of-type + + // testSelectorWithNot + { select: '#p a:not(:first-of-type)', expect: { ids: ['link_2'] } }, // first-of-type + { select: '#p a:not(:last-of-type)', expect: { ids: ['link_1'] } }, // last-of-type + { select: '#p a:not(:nth-of-type(1))', expect: { ids: ['link_2'] } }, // nth-of-type + { select: '#p a:not(:nth-last-of-type(1))', expect: { ids: ['link_1'] } }, // nth-last-of-type + { select: '#p a:not([rel~=nofollow])', expect: { ids: ['link_2'] } }, // attribute 1 + { select: '#p a:not([rel^=external])', expect: { ids: ['link_2'] } }, // attribute 2 + { select: '#p a:not([rel$=nofollow])', expect: { ids: ['link_2'] } }, // attribute 3 + { select: '#p a:not([rel$="nofollow"]) > em', expect: { ids: ['em'] } }, // attribute 4 + { select: '#list li:not(#item_1):not(#item_3)', expect: { ids: ['item_2'] } }, // adjacent :not clauses + { select: '#grandfather > div:not(#uncle) #son', expect: { ids: ['son'] } }, + { select: '#p a:not([rel$="nofollow"]) em', expect: { ids: ['em'] } }, // attribute 4 + all descendants + { select: '#p a:not([rel$="nofollow"])>em', expect: { ids: ['em'] } }, // attribute 4 (without whitespace) + + // testSelectorWithEnabledDisabledChecked + { select: '#troubleForm > *:disabled', expect: { ids: ['disabled_text_field'] } }, + { select: '#troubleForm > *:enabled', expect: { ids: ['hidden', 'enabled_text_field', 'checked_box', 'unchecked_box', 'checked_radio', 'unchecked_radio'] } }, + { select: '#troubleForm *:checked', expect: { ids: ['checked_box', 'checked_radio'] } }, + + // testIdenticalResultsFromEquivalentSelectors + { select: 'div.brothers', expect: { equivalentCase: { select: 'div[class~=brothers]' } } }, + { select: 'div.brothers', expect: { equivalentCase: { select: 'div[class~=brothers].brothers' } } }, + { select: 'div:not(.brothers)', expect: { equivalentCase: { select: 'div:not([class~=brothers])' } } }, + { select: 'li ~ li', expect: { equivalentCase: { select: 'li:not(:first-child)' } } }, + { select: 'ul > li', expect: { equivalentCase: { select: 'ul > li:nth-child(n)' } } }, + { select: 'ul > li:nth-child(even)', expect: { equivalentCase: { select: 'ul > li:nth-child(2n)' } } }, + { select: 'ul > li:nth-child(odd)', expect: { equivalentCase: { select: 'ul > li:nth-child(2n+1)' } } }, + { select: 'ul > li:first-child', expect: { equivalentCase: { select: 'ul > li:nth-child(1)' } } }, + { select: 'ul > li:last-child', expect: { equivalentCase: { select: 'ul > li:nth-last-child(1)' } } }, + { select: 'ul > li:nth-child(n-128)', expect: { equivalentCase: { select: 'ul > li' } } }, + { select: 'ul > li:nth-child(n-999)', expect: { equivalentCase: { select: 'ul > li' } } }, + { select: 'ul>li', expect: { equivalentCase: { select: 'ul > li' } } }, + { select: '#p a:not([rel$="nofollow"])>em', expect: { equivalentCase: { select: '#p a:not([rel$="nofollow"]) > em' } } }, + + // testSelectorsThatShouldReturnNothing + { select: 'span:empty > *', expect: { count: 0, ids: [] } }, + { select: 'div.brothers:not(.brothers)', expect: { count: 0, ids: [] } }, + { select: '#level2_2 :only-child:not(:last-child)', expect: { count: 0, ids: [] } }, + { select: '#level2_2 :only-child:not(:first-child)', expect: { count: 0, ids: [] } }, + + // testCommasFor$$ + { select: '#list, .first, *[xml:lang="es-us"], #troubleForm', expect: { ids: ['p', 'link_1', 'list', 'item_1', 'item_3', 'troubleForm'] }, status: 'fixme' }, + { select: 'form[title*="commas,"], input[value="#commaOne,#commaTwo"]', expect: { ids: ['commaParent', 'commaChild'] } }, + + // testElementDownWithDotAndColon + { select: '#dupContainer\\.withdot\\:active #dupL4_dotcolon', expect: { ids: ['dupL4_dotcolon'] } } + ], + }, + + { + name: 'empty pseudo after mutation', + markupMode: 'html-document', + markup: nwsapiProtoTestHtml, + setupPage: async (page) => { + await page.evaluate(() => { + const el = document.getElementById('level3_1'); + if (el) el.innerHTML = ''; + }); + }, + cases: [ + // testSelectorWithEmpty + { select: '#level1 *:empty', expect: { ids: ['level3_1', 'level3_2', 'level2_3'] } }, + { select: '#level_only_child:empty', expect: { count: 0, ids: [] } }, // newlines count as content + ], + }, + + { + name: 'selectors on detached nodes', + markup: '', + cases: [], + setupPage: async (page) => { + const result = await page.evaluate(() => { + const wrapper = document.createElement('div'); + wrapper.innerHTML = "
    "; + + return { + byAttr: NW.Dom.select('[id=myTD]', wrapper).map(el => el.getAttribute('id')), + byTag: NW.Dom.select('td', wrapper).map(el => el.getAttribute('id')), + byId: NW.Dom.select('#myTD', wrapper).map(el => el.getAttribute('id')), + }; + }); + + expect(result.byAttr).toEqual(['myTD']); + expect(result.byTag).toEqual(['myTD']); + expect(result.byId).toEqual(['myTD']); + }, + }, + + { + name: 'descendant selector on dynamic subtree', + markup: '', + cases: [], + setupPage: async (page) => { + const result = await page.evaluate(() => { + const el = document.createElement('div'); + el.innerHTML = '
    '; + document.body.appendChild(el); + + const nativeCount = el.querySelectorAll('ul li').length; + const nwCount = NW.Dom.select('ul li', el).length; + + document.body.removeChild(el); + return { nativeCount, nwCount }; + }); + + expect(result.nativeCount).toBe(2); + expect(result.nwCount).toBe(2); + }, + }, +]); \ No newline at end of file diff --git a/test_new/browser/quirks.test.ts b/test_new/browser/quirks.test.ts new file mode 100644 index 0000000..c6aa462 --- /dev/null +++ b/test_new/browser/quirks.test.ts @@ -0,0 +1,61 @@ +import { runScenarios } from "./harness/scenarios"; + +runScenarios('quirks', 'normal', [ + { + name: 'class token matching in standard mode', + markupMode: 'html-document', + markup: ` + + + + + + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + `, + cases: [ + { select: '#dom [class~=foobar]', expect: { ids: ['d1'] } }, + { select: '#qsa [class~=foobar]', expect: { ids: ['q1'] } }, + { select: '#dom [class~=foobar i]', expect: { ids: ['d1', 'd2', 'd3'] } }, + { select: '#qsa [class~=foobar i]', expect: { ids: ['q1', 'q2', 'q3'] } }, + ], + }, + { + name: 'class token matching in quirks mode', + markupMode: 'html-document', + markup: ` + + + + + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + `, + cases: [ + { select: '#dom [class~=foobar]', expect: { ids: ['d1'] } }, + { select: '#qsa [class~=foobar]', expect: { ids: ['q1'] } }, + { select: '#dom [class~=foobar i]', expect: { ids: ['d1', 'd2', 'd3'] } }, + { select: '#qsa [class~=foobar i]', expect: { ids: ['q1', 'q2', 'q3'] } }, + ], + } +]); diff --git a/test_new/browser/scope.test.ts b/test_new/browser/scope.test.ts new file mode 100644 index 0000000..5b758a4 --- /dev/null +++ b/test_new/browser/scope.test.ts @@ -0,0 +1,127 @@ +import { runScenarios } from "./harness/scenarios"; + +runScenarios('scope', 'normal', [ + { + name: 'scope-01a', + markup: ` + + `, + cases: [ + { select: 'ul a', expect: { count: 2 } }, + { select: '#scope', expect: { count: 1 } }, + { select: 'a', ref: { by: 'id', id: 'scope' }, expect: { count: 1 } }, + ], + }, + + { + name: 'scope-01b', + markup: ` + + `, + cases: [ + { select: '#scope', expect: { count: 1 } }, + { select: ':scope ul a', ref: { by: 'id', id: 'scope' }, expect: { count: 0, ids: [] } }, + { select: ':scope body ul a', ref: { by: 'id', id: 'scope' }, expect: { count: 0, ids: [] } }, + { select: ':scope a', ref: { by: 'id', id: 'scope' }, expect: { count: 1 } }, + ], + }, + + { + name: 'scope-02a/02b', + markup: ` +
    +
    +
    +
    + `, + cases: [ + { select: '.a', expect: { count: 1 } }, + { select: 'body div', ref: { by: 'first', selector: '.a' }, expect: { count: 2 } }, + { select: ':scope body div', ref: { by: 'first', selector: '.a' }, expect: { count: 0, ids: [] } }, + ], + }, + + { + name: 'scope-03a', + markup: ` +
    +

    + hello +

    +
    + `, + cases: [ + { select: 'div', expect: { count: 1 } }, + { select: ':scope > p', ref: { by: 'first', selector: 'div' }, expect: { count: 1 } }, + { select: ':scope > span', ref: { by: 'first', selector: 'div' }, expect: { count: 0, ids: [] } }, + ], + }, + + { + name: 'scope-03b', + markup: ` +
    +
    +
    +
    + `, + cases: [ + { select: 'body div', ref: { by: 'first', selector: '.a' }, expect: { count: 2 } }, + { select: ':scope body div', ref: { by: 'first', selector: '.a' }, expect: { count: 0, ids: [] } }, + { select: ':scope > .a1, :scope > .a2', ref: { by: 'first', selector: '.a' }, expect: { count: 2 } }, + ], + }, + + { + name: 'scope-04a', + markupMode: 'html-document', + markup: ` + + + + test nwsapi + + + + + +
    + + + `, + cases: [ + { select: ':scope > [data-test="foo"]', ref: { by: 'first', selector: 'body' }, expect: { count: 1 }, status: 'fixme' }, + ], + }, + + { + name: 'scope-04b', + markup: ` +
    +
    +
    +
    +
    +
    + `, + cases: [ + { + select: ':scope > div', + ref: { by: 'first', selector: 'div' }, + expect: { + classes: ['outer', 'other-outer'] + }, + status: 'fixme', + }, + ], + }, + +]); \ No newline at end of file diff --git a/test_new/browser/scotch.test.ts b/test_new/browser/scotch.test.ts new file mode 100644 index 0000000..3e87af2 --- /dev/null +++ b/test_new/browser/scotch.test.ts @@ -0,0 +1,472 @@ +import { Page } from "playwright/test"; +import { runScenarios } from "./harness/scenarios"; + +const html = ` + + + + + NWSAPI Tests + + + + + + +
    +
    + + +
    + + `; + +const setupNw = async (page: Page) => { + await page.evaluate(() => { + NW.Dom.configure({ + 'SIMPLENOT': true, + 'VERBOSITY': true + }); + }); +} + +runScenarios('scotch', 'normal', [ + { + name: 'Basic Selectors', + markup: html, + markupMode: 'html-document', + setupPage: setupNw, + cases: [ + // * — Universal selector + { select: '*' }, + + // E — Type selector + { select: 'li' }, + { select: 'strong', ref: { by: 'id', id: 'fixtures' }, expect: { ids: ['strong'] } }, + { select: 'nonexistent', expect: { count: 0 } }, + + // #id — ID selector + { select: '#fixtures', expect: { ids: ['fixtures'] } }, + { select: 'nonexistent', expect: { count: 0 } }, + { select: '#troubleForm', expect: { ids: ['troubleForm'] } }, + + // .class — Class selector + { select: '.first', expect: { ids: ['p', 'link_1', 'item_1'] } }, + { select: '.second', expect: { count: 0 } }, + + // E#id + { select: 'strong#strong', expect: { ids: ['strong'] } }, + { select: 'p#strong', expect: { count: 0 } }, + + // E.class + { select: 'a.internal', expect: { ids: ['link_1', 'link_2'] } }, + { select: 'a.internal.highlight', expect: { ids: ['link_2'] } }, + { select: 'a.highlight.internal', expect: { ids: ['link_2'] } }, + { select: 'a.highlight.internal.nonexistent', expect: { count: 0 } }, + + // #id.class + { select: '#link_2.internal', expect: { ids: ['link_2'] } }, + { select: '.internal#link_2', expect: { ids: ['link_2'] } }, + { select: '#link_2.internal.highlight', expect: { ids: ['link_2'] } }, + { select: '#link_2.internal.nonexistent', expect: { count: 0 } }, + + // E#id.class + { select: 'a#link_2.internal', expect: { ids: ['link_2'] } }, + { select: 'a.internal#link_2', expect: { ids: ['link_2'] } }, + { select: 'li#item_1.first', expect: { ids: ['item_1'] } }, + { select: 'li#item_1.nonexistent', expect: { count: 0 } }, + { select: 'li#item_1.first.nonexistent', expect: { count: 0 } }, + ], + }, + { + name: 'Attribute Selectors', + markup: html, + markupMode: 'html-document', + setupPage: setupNw, + cases: [ + // [foo] + { select: '[href]', ref: { by: 'first', selector: 'body' }, expect: { equivalentCase: { select: 'a[href]', ref: { by: 'first', selector: 'body' } } } }, + { select: '[class~=internal]', expect: { equivalentCase: { select: 'a[class~="internal"]' } } }, + { select: '[id]', expect: { equivalentCase: { select: '*[id]' } } }, + { select: '[type=radio]', expect: { ids: ['checked_radio', 'unchecked_radio'] } }, + { select: '[type=checkbox]', expect: { equivalentCase: { select: '*[type=checkbox]' } } }, + { select: '[title]', expect: { ids: ['with_title', 'commaParent'] } }, + { select: '#troubleForm [type=radio]', expect: { equivalentCase: { select: '#troubleForm *[type=radio]' } } }, + { select: '#troubleForm [type]', expect: { equivalentCase: { select: '#troubleForm *[type]' } } }, + + // E[foo] + { select: 'h1[class]', expect: { equivalentCase: { select: '#fixtures h1' } } }, + { select: 'h1[CLASS]', expect: { equivalentCase: { select: '#fixtures h1' } } }, + { select: 'li#item_3[class]', expect: { ids: ['item_3'] } }, + { select: '#troubleForm2 input[name="brackets[5][]"]', expect: { ids: ['chk_1', 'chk_2'] } }, + { select: '#troubleForm2 input[name="brackets[5][]"]:checked', expect: { ids: ['chk_1'] } }, + { select: 'cite[title="hello world!"]', expect: { ids: ['with_title'] } }, + { select: '[xml:lang]', expect: { count: 2, includesIds: ['item_3'], equivalentCase: { select: '*[xml:lang]' } }, status: 'fixme' }, + { select: '*[xml:lang]', expect: { count: 2, includesIds: ['item_3'] }, status: 'fixme' }, + + // E[foo="bar"] + { select: 'a[href="#"]', expect: { ids: ['link_1', 'link_2', 'link_3'] } }, + { select: 'a[href=#]', expect: { throws: true } }, + { select: '#troubleForm2 input[name="brackets[5][]"][value="2"]', expect: { ids: ['chk_2'] } }, + + // E[foo~="bar"] + { select: 'a[class~="internal"]', expect: { ids: ['link_1', 'link_2'] } }, + { select: 'a[class~=internal]', expect: { ids: ['link_1', 'link_2'] } }, + { select: 'a[class~=external][href="#"]', expect: { ids: ['link_3'] } }, + + // E[foo|="en"] + { select: '*[xml:lang|="es"]', expect: { ids: ['item_3'] }, status: 'fixme' }, + { select: '*[xml:lang|="ES"]', expect: { ids: ['item_3'] }, status: 'fixme' }, + + // E[foo^="bar"] + { select: 'div[class^=bro]', expect: { ids: ['father', 'uncle'] } }, + { select: '#level1 *[id^="level2_"]', expect: { ids: ['level2_1', 'level2_2', 'level2_3'] } }, + { select: '#level1 *[id^=level2_]', expect: { ids: ['level2_1', 'level2_2', 'level2_3'] } }, + + // benchmark(function(){ select('#level1 *[id^=level2_]'); }, 1000) + { select: '#level1 *[id^=level2_]', expect: { ids: ['level2_1', 'level2_2', 'level2_3'] } }, + + // E[foo$="bar"] + { select: 'div[class$=men]', expect: { ids: ['father', 'uncle'] } }, + { select: '#level1 *[id$="_1"]', expect: { ids: ['level2_1', 'level3_1'] } }, + { select: '#level1 *[id$=_1]', expect: { ids: ['level2_1', 'level3_1'] } }, + + // benchmark(function(){ select('#level1 *[id$=_1]'); }, 1000) + { select: '#level1 *[id$=_1]', expect: { ids: ['level2_1', 'level3_1'] } }, + + // E[foo*="bar"] + { select: 'div[class*="ers m"]', expect: { ids: ['father', 'uncle'] } }, + { select: '#level1 *[id*="2"]', expect: { ids: ['level2_1', 'level3_2', 'level2_2', 'level2_3'] } }, + { select: '#level1 *[id*=2]', expect: { throws: true } }, + // benchmark(function(){ select('#level1 *[id*=2]'); }, 1000) + { select: '#level1 *[id*=2]', expect: { throws: true } }, + + // E[id=-1] — should throw SYNTAX_ERR + // { selector: '#level1 *[id=-1]', expect: { throws: true }, }, + { select: '#level1 *[id=9]', expect: { throws: true } }, + + // E[class=-45deg] — should throw SYNTAX_ERR + // { selector: '#level1 *[class=-45deg]', expect: { throws: true } }, + + // E[class=8mm] — should throw SYNTAX_ERR + { select: '#level1 *[class=8mm]', expect: { throws: true } }, + ], + }, + + { + name: 'Attribute Selectors — invalid unquoted values', + markup: html, + markupMode: 'html-document', + setupPage: setupNw, + status: 'fixme', + cases: [ + // should throw SYNTAX_ERR + { select: '#level1 *[id=-1]', expect: { throws: true } }, + { select: '#level1 *[id=9]', expect: { throws: true } }, + { select: '#level1 *[class=-45deg]', expect: { throws: true } }, + { select: '#level1 *[class=8mm]', expect: { throws: true } }, + ], + }, + + { + name: 'Structural pseudo-classes', + markup: html, + setupPage: setupNw, + cases: [ + // E:first-child + { select: '#level1>*:first-child', expect: { ids: ['level2_1'] } }, + { select: '#level1 *:first-child', expect: { ids: ['level2_1', 'level3_1', 'level_only_child'] } }, + { select: '#level1>div:first-child', expect: { count: 0 } }, + { select: '#level1 span:first-child', expect: { ids: ['level2_1', 'level3_1'] } }, + { select: '#level1:first-child', expect: { count: 0 } }, + + // benchmark(function(){ select('#level1 *:first-child'); }, 1000) + { select: '#level1 *:first-child', expect: { ids: ['level2_1', 'level3_1', 'level_only_child'] } }, + + // E:last-child + { select: '#level1>*:last-child', expect: { ids: ['level2_3'] } }, + { select: '#level1 *:last-child', expect: { ids: ['level3_2', 'level_only_child', 'level2_3'] } }, + { select: '#level1>div:last-child', expect: { ids: ['level2_3'] } }, + { select: '#level1 div:last-child', expect: { ids: ['level2_3'] } }, + { select: '#level1>span:last-child', expect: { count: 0 } }, + + // benchmark(function(){ select('#level1 *:last-child'); }, 1000) + { select: '#level1 *:last-child', expect: { ids: ['level3_2', 'level_only_child', 'level2_3'] } }, + + // E:nth-child(n) + { select: '#p *:nth-child(3)', expect: { ids: ['link_2'] } }, + { select: '#p a:nth-child(3)', expect: { ids: ['link_2'] } }, + { select: '#list > li:nth-child(n+2)', expect: { ids: ['item_2', 'item_3'] } }, + { select: '#list > li:nth-child(-n+2)', expect: { ids: ['item_1', 'item_2'] } }, + + // E:nth-of-type(n) + { select: '#p a:nth-of-type(2)', expect: { ids: ['link_2'] } }, + { select: '#p a:nth-of-type(1)', expect: { ids: ['link_1'] } }, + + // E:nth-last-of-type(n) + { select: '#p a:nth-last-of-type(1)', expect: { ids: ['link_2'] } }, + + // E:first-of-type + { select: '#p a:first-of-type', expect: { ids: ['link_1'] } }, + + // E:last-of-type + { select: '#p a:last-of-type', expect: { ids: ['link_2'] } }, + + // E:only-child + { select: '#level1 *:only-child', expect: { ids: ['level_only_child'] } }, + { select: '#level1>*:only-child', expect: { count: 0 } }, + { select: '#level1:only-child', expect: { count: 0 } }, + { select: '#level2_2 :only-child:not(:last-child)', expect: { count: 0 } }, + { select: '#level2_2 :only-child:not(:first-child)', expect: { count: 0 } }, + + // benchmark(function(){ select('#level1 *:only-child'); }, 1000) + { select: '#level1 *:only-child', expect: { ids: ['level_only_child'] } }, + ], + }, + + { + name: 'Structural pseudo-classes — E:empty', + markup: html, + markupMode: 'html-document', + setupPage: async (page) => { + await setupNw(page); + await page.evaluate(() => { + const el = document.getElementById('level3_1'); + if (el) el.innerHTML = ''; + }); + }, + cases: [ + // E:empty + { select: '#level1 *:empty', expect: { ids: ['level3_1', 'level3_2', 'level2_3'] } }, + { select: '#level_only_child:empty', expect: { count: 0 } }, + { select: 'span:empty > *', expect: { count: 0 } }, + ], + }, + + { + name: 'E:not(s)', + markup: html, + markupMode: 'html-document', + setupPage: setupNw, + cases: [ + { select: 'a:not([href="#"])', expect: { count: 0 } }, + { select: 'div.brothers:not(.brothers)', expect: { count: 0 } }, + { select: 'a[class~=external]:not([href="#"])', expect: { count: 0 } }, + { select: '#p a:not(:first-of-type)', expect: { ids: ['link_2'] } }, + { select: '#p a:not(:last-of-type)', expect: { ids: ['link_1'] } }, + { select: '#p a:not(:nth-of-type(1))', expect: { ids: ['link_2'] } }, + { select: '#p a:not(:nth-last-of-type(1))', expect: { ids: ['link_1'] } }, + { select: '#p a:not([rel~=nofollow])', expect: { ids: ['link_2'] } }, + { select: '#p a:not([rel^=external])', expect: { ids: ['link_2'] } }, + { select: '#p a:not([rel$=nofollow])', expect: { ids: ['link_2'] } }, + { select: '#p a:not([rel$="nofollow"]) > em', expect: { ids: ['em'] } }, + { select: '#list li:not(#item_1):not(#item_3)', expect: { ids: ['item_2'] } }, + { select: '#grandfather > div:not(#uncle) #son', expect: { ids: ['son'] } }, + { select: '#p a:not([rel$="nofollow"]) em', expect: { ids: ['em'] } }, + { select: '#p a:not([rel$="nofollow"])>em', expect: { ids: ['em'] } }, + ], + }, + + { + name: 'UI element states pseudo-classes', + markup: html, + markupMode: 'html-document', + setupPage: setupNw, + cases: [ + // E:disabled + { select: '#troubleForm > p > *:disabled', expect: { ids: ['disabled_text_field'] } }, + + // E:checked + { select: '#troubleForm *:checked', expect: { ids: ['checked_box', 'checked_radio'] } }, + ], + }, + + { + name: 'Combinators', + markup: html, + markupMode: 'html-document', + setupPage: setupNw, + cases: [ + // E F — Descendant + { select: '#fixtures a *', expect: { ids: ['em2', 'em', 'span'] } }, + { select: 'div#fixtures p', expect: { includesIds: ['p'] } }, + + // E + F — Adjacent sibling + { select: 'div.brothers + div.brothers', expect: { includesIds: ['uncle'] } }, + { select: 'div.brothers + div', expect: { includesIds: ['uncle'] } }, + { select: '#level2_1+span', expect: { includesIds: ['level2_2'] } }, + { select: '#level2_1 + span', expect: { includesIds: ['level2_2'] } }, + { select: '#level2_1 + *', expect: { includesIds: ['level2_2'] } }, + { select: '#level2_2 + span', expect: { count: 0 } }, + { select: '#level3_1 + span', expect: { includesIds: ['level3_2'] } }, + { select: '#level3_1 + *', expect: { includesIds: ['level3_2'] } }, + { select: '#level3_2 + *', expect: { count: 0 } }, + { select: '#level3_1 + em', expect: { count: 0 } }, + + // benchmark(function(){ select('#level3_1 + span'); }, 1000) + { select: '#level3_1 + span', expect: { includesIds: ['level3_2'] } }, + + // E > F — Child + { select: 'p.first > a', expect: { ids: ['link_1', 'link_2'] } }, + { select: 'div#grandfather > div', expect: { ids: ['father', 'uncle'] } }, + { select: '#level1>span', expect: { ids: ['level2_1', 'level2_2'] } }, + { select: '#level1 > span', expect: { ids: ['level2_1', 'level2_2'] } }, + { select: '#level2_1 > *', expect: { ids: ['level3_1', 'level3_2'] } }, + { select: 'div > #nonexistent', expect: { count: 0 } }, + + // benchmark(function(){ select('#level1 > span'); }, 1000) + { select: '#level1 > span', expect: { ids: ['level2_1', 'level2_2'] } }, + + // E ~ F — General sibling + { select: 'h1 ~ ul', expect: { includesIds: ['list'] } }, + { select: '#level2_2 ~ span', expect: { count: 0 } }, + { select: '#level3_2 ~ *', expect: { count: 0 } }, + { select: '#level3_1 ~ em', expect: { count: 0 } }, + { select: 'div ~ #level3_2', expect: { count: 0 } }, + { select: 'div ~ #level2_3', expect: { count: 0 } }, + { select: '#level2_1 ~ span', expect: { includesIds: ['level2_2'] } }, + { select: '#level2_1 ~ *', expect: { ids: ['level2_2', 'level2_3'] } }, + { select: '#level3_1 ~ #level3_2', expect: { includesIds: ['level3_2'] } }, + { select: 'span ~ #level3_2', expect: { includesIds: ['level3_2'] } }, + + // benchmark(function(){ select('#level2_1 ~ span'); }, 1000) + { select: '#level2_1 ~ span', expect: { includesIds: ['level2_2'] } }, + ], + }, + + { + name: 'NW.Dom.match', + markup: html, + markupMode: 'html-document', + setupPage: setupNw, + cases: [ + { select: 'span', expect: { includesIds: ['dupL1'] } }, + { select: 'span#dupL1', expect: { includesIds: ['dupL1'] } }, + { select: 'div > span', expect: { includesIds: ['dupL1'] } }, // child combinator + { select: '#dupContainer span', expect: { includesIds: ['dupL1'] } }, // descendant combinator + { select: '#dupL1', expect: { includesIds: ['dupL1'] } }, // ID only + { select: 'span.span_foo', expect: { includesIds: ['dupL1'] } }, // class name 1 + { select: 'span.span_bar', expect: { includesIds: ['dupL1'] } }, // class name 2 + { select: 'span:first-child', expect: { includesIds: ['dupL1'] } }, // first-child pseudoclass + + { select: 'span.span_wtf', expect: { excludesIds: ['dupL1'] } }, // bogus class name + { select: '#dupL2', expect: { excludesIds: ['dupL1'] } }, // different ID + { select: 'div', expect: { excludesIds: ['dupL1'] } }, // different tag name + { select: 'span span', expect: { excludesIds: ['dupL1'] } }, // different ancestry + { select: 'span > span', expect: { excludesIds: ['dupL1'] } }, // different parent + { select: 'span:nth-child(5)', expect: { excludesIds: ['dupL1'] } }, // different pseudoclass + + { select: 'a[rel^=external]', expect: { includesIds: ['link_1'], excludesIds: ['link_2'] } }, + { select: 'a[rel^="external"]', expect: { includesIds: ['link_1'] } }, + { select: "a[rel^='external']", expect: { includesIds: ['link_1'] } }, + ], + }, + + { + name: 'Equivalent Selectors', + markup: html, + markupMode: 'html-document', + setupPage: setupNw, + cases: [ + { select: 'div.brothers', expect: { equivalentCase: { select: 'div[class~=brothers]' } } }, + { select: 'div.brothers', expect: { equivalentCase: { select: 'div[class~=brothers].brothers' } } }, + { select: 'div:not(.brothers)', expect: { equivalentCase: { select: 'div:not([class~=brothers])' } } }, + { select: 'li ~ li', expect: { equivalentCase: { select: 'li:not(:first-child)' } } }, + { select: 'ul > li', expect: { equivalentCase: { select: 'ul > li:nth-child(n)' } } }, + { select: 'ul > li:nth-child(even)', expect: { equivalentCase: { select: 'ul > li:nth-child(2n)' } } }, + { select: 'ul > li:nth-child(odd)', expect: { equivalentCase: { select: 'ul > li:nth-child(2n+1)' } } }, + { select: 'ul > li:first-child', expect: { equivalentCase: { select: 'ul > li:nth-child(1)' } } }, + { select: 'ul > li:last-child', expect: { equivalentCase: { select: 'ul > li:nth-last-child(1)' } } }, + { select: 'ul > li:nth-child(n-128)', expect: { equivalentCase: { select: 'ul > li' } } }, + { select: 'ul>li', expect: { equivalentCase: { select: 'ul > li' } } }, + { select: '#p a:not([rel$="nofollow"])>em', expect: { equivalentCase: { select: '#p a:not([rel$="nofollow"]) > em' } } }, + ], + }, + + { + name: 'Multiple Selectors', + markup: html, + markupMode: 'html-document', + setupPage: setupNw, + cases: [ + { select: '#list, .first,*[xml:lang="es-us"] , #troubleForm', expect: { ids: ['p', 'link_1', 'list', 'item_1', 'item_3', 'troubleForm'] }, status: 'fixme' }, + { select: '#list, .first, *[xml:lang="es-us"], #troubleForm', expect: { ids: ['p', 'link_1', 'list', 'item_1', 'item_3', 'troubleForm'] }, status: 'fixme' }, + { select: 'form[title*="commas,"], input[value="#commaOne,#commaTwo"]', expect: { ids: ['commaParent', 'commaChild'] } }, + { select: 'form[title*="commas,"], input[value="#commaOne,#commaTwo"]', expect: { ids: ['commaParent', 'commaChild'] } }, + ], + }, +]); diff --git a/test_new/browser/slick.test.ts b/test_new/browser/slick.test.ts new file mode 100644 index 0000000..c0d1d71 --- /dev/null +++ b/test_new/browser/slick.test.ts @@ -0,0 +1,2294 @@ +import { expect, type Page } from "@playwright/test"; +import { readFileSync } from 'node:fs'; +import { runScenarios, type Scenario, type TestCase } from "./harness/scenarios"; + +const fixtures = { + htmlTransitional: readFileSync('test_new/browser/fixtures/slick/template-transitional.html', 'utf8'), + htmlStandard: readFileSync('test_new/browser/fixtures/slick/template-standard.html', 'utf8'), + htmlAlmost: readFileSync('test_new/browser/fixtures/slick/template-almost.html', 'utf8'), + htmlQuirks: readFileSync('test_new/browser/fixtures/slick/template-quirks.html', 'utf8'), + xhtml: readFileSync('test_new/browser/fixtures/slick/template.xhtml', 'utf8'), + xml: readFileSync('test_new/browser/fixtures/slick/template.xml', 'utf8'), + svg: readFileSync('test_new/browser/fixtures/slick/MooTools_Logo.svg', 'utf8'), +} as const; + +type TemplateKey = 'html-standard' | 'html-almost' | 'html-quirks' | 'xhtml' | 'html-transitional' | 'xml' | 'svg'; +type TemplateTuple = readonly [TemplateKey, string]; + +const allTemplates: TemplateTuple[] = [ + ['html-transitional', fixtures.htmlTransitional], + ['html-standard', fixtures.htmlStandard], + ['html-almost', fixtures.htmlAlmost], + ['html-quirks', fixtures.htmlQuirks], + ['xhtml', fixtures.xhtml], + ['xml', fixtures.xml], + ['svg', fixtures.svg], +] as const; + +const xmlTemplates: TemplateTuple[] = [ + ['xhtml', fixtures.xhtml], + ['xml', fixtures.xml], + ['svg', fixtures.svg], +] as const; + +const htmlTemplates: TemplateTuple[] = [ + ['html-transitional', fixtures.htmlTransitional], + ['html-standard', fixtures.htmlStandard], + ['html-almost', fixtures.htmlAlmost], + ['html-quirks', fixtures.htmlQuirks], +] as const; + +const browserBugTemplates: TemplateTuple[] = [ + ['html-standard', fixtures.htmlStandard], + ['html-almost', fixtures.htmlAlmost], + ['html-quirks', fixtures.htmlQuirks], + ['xhtml', fixtures.xhtml], +] as const; + +type BugWin = Window & typeof globalThis & { + __slick: { + getHost(): HTMLElement; + resetHost(): HTMLElement; + setHostHTML(html: string): HTMLElement; + add(tag: string, attrs?: Record, parent?: Element): HTMLElement; + }; +}; + +runScenarios('slick', 'normal', [ + { + name: 'bootstrap/isxml-legacy-xml', + markupMode: 'xml-document', + markup: ``, + setupPage: async (page) => { + const isXml = await page.evaluate(() => { + const legacyIsXML = (element: Document | Element) => { + const ownerDocument = element.ownerDocument || element; + return !('body' in ownerDocument) || + !('innerHTML' in ownerDocument.documentElement) || + ownerDocument.createElement('DiV').nodeName === 'DiV'; + }; + + return legacyIsXML(document); + }); + + expect(isXml).toBe(true); + }, + cases: [], + }, + + { + name: 'bootstrap/isxml-legacy-html', + markupMode: 'html-document', + markup: `
    `, + setupPage: async (page) => { + const isXml = await page.evaluate(() => { + const legacyIsXML = (element: Document | Element) => { + const ownerDocument = element.ownerDocument || element; + return !('body' in ownerDocument) || + !('innerHTML' in ownerDocument.documentElement) || + ownerDocument.createElement('DiV').nodeName === 'DiV'; + }; + + return legacyIsXML(document); + }); + + expect(isXml).toBe(false); + }, + cases: [], + }, + + { + name: 'api/context-basics', + markup: ` +
    +
    + + +
    + +
    `, + cases: [ + { select: '.x', ref: { by: 'id', id: 'scope' }, expect: { count: 1 } }, + { select: '*', ref: { by: 'documentElement' }, expect: { count: 7 } }, + { byTag: '*', ref: { by: 'id', id: 'scope' }, expect: { count: 2 } }, + ], + }, + + ...browserBugTemplates.map(([name, markup]) => ( + { + name: `browser-bugs/${name}`, + markup, + markupMode: 'html-document', + setupPage: async (page) => { + await initPage(page, name); + }, + steps: [ + { + // getElementsByName Should match name attribute + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { id: 'getelementsbyname', type: 'password', class: 'tmpNode2' }); + win.__slick.add('input', { name: 'getelementsbyname', type: 'text', class: 'tmpNode1' }); + }); + }, + cases: [ + // Not migrated as a real case because byName is not supported by NW and + // { byName: 'getelementsbyname', expect: { count: 1, classes: ['tmpNode1'] }, engines: ['native'] }, + ], + }, + { + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { name: 'getelementsbyname', type: 'text', class: 'tmpNode1' }); + win.__slick.add('input', { id: 'getelementsbyname', type: 'password', class: 'tmpNode2' }); + }); + }, + cases: [ + // Not migrated as a real case because byName is not supported by NW and + // { byName: 'getelementsbyname', expect: { count: 1, classes: ['tmpNode1'] }, engines: ['native'] }, + ], + }, + + { + // getElementsByName Should NOT match id attribute + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { id: 'getelementsbyname', type: 'password', class: 'tmpNode2' }); + win.__slick.add('input', { name: 'getelementsbyname', type: 'text', class: 'tmpNode1' }); + }); + }, + cases: [ + // Not migrated as a real case because byName is not supported by NW and + // { byName: 'getelementsbyname', expect: { count: 1, classes: ['tmpNode1'] }, engines: ['native'] }, + ], + }, + { + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { name: 'getelementsbyname', type: 'text', class: 'tmpNode1' }); + win.__slick.add('input', { id: 'getelementsbyname', type: 'password', class: 'tmpNode2' }); + }); + }, + cases: [ + // Not migrated as a real case because byName is not supported by NW and + // { byName: 'getelementsbyname', expect: { count: 1, classes: ['tmpNode1'] }, engines: ['native'] }, + ], + }, + + { + // getElementsByName Should match name attribute, using innerHTML + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + const host = win.__slick.resetHost(); + host.innerHTML = + '' + + ''; + }); + }, + cases: [ + // Not migrated as a real case because byName is not supported by NW and + // { byName: 'getelementsbyname', expect: { count: 1, classes: ['tmpNode1'] }, engines: ['native'] }, + ], + }, + { + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + const host = win.__slick.resetHost(); + host.innerHTML = + '' + + ''; + }); + }, + cases: [ + // Not migrated as a real case because byName is not supported by NW and + // { byName: 'getelementsbyname', expect: { count: 1, classes: ['tmpNode1'] }, engines: ['native'] }, + ], + }, + + { + // getElementById Should NOT match name attribute + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { name: 'getelementbyid', type: 'text', class: 'tmpNode1' }); + win.__slick.add('input', { id: 'getelementbyid', type: 'password', class: 'tmpNode2' }); + }); + }, + cases: [ + { byId: 'getelementbyid', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode2'] } }, + ], + }, + { + // getElementById Should match id attribute + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { name: 'getelementbyid', type: 'text', class: 'tmpNode1' }); + win.__slick.add('input', { id: 'getelementbyid', type: 'password', class: 'tmpNode2' }); + }); + }, + cases: [ + { byId: 'getelementbyid', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode2'] } }, + ], + }, + { + // getElementsById Should match id attribute, using innerHTML + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + const host = win.__slick.resetHost(); + host.innerHTML = + '' + + ''; + }); + }, + cases: [ + { byId: 'getelementbyid', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode2'] } }, + ], + }, + + { + // getElementsByClassName Should match second class name + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { class: 'getelementsbyclassname secondclass', type: 'text' }); + }); + }, + cases: [ + { byClass: 'secondclass', ref: { by: 'id', id: 'host' }, expect: { count: 1 } }, + ], + }, + { + // getElementsByClassName Should match second class name, using innerHTML + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + const host = win.__slick.resetHost(); + host.innerHTML = ''; + }); + }, + cases: [ + { byClass: 'secondclass', ref: { by: 'id', id: 'host' }, expect: { count: 1 } }, + ], + }, + { + // getElementsByClassName Should not cache results + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + const host = win.__slick.resetHost(); + host.innerHTML = ''; + host.getElementsByClassName('b').length; // force initial access, matching original intent + (host.firstChild as Element).className = 'b'; + }); + }, + cases: [ + { byClass: 'b', ref: { by: 'id', id: 'host' }, expect: { count: 2 } }, + ], + }, + + { + // getElementsByTagName Should not return comment nodes with * selector + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + const host = win.__slick.resetHost(); + host.appendChild(document.createComment('')); + }); + }, + cases: [ + { byTag: '*', ref: { by: 'id', id: 'host' }, expect: { count: 0 } }, + ], + }, + { + // getElementsByTagName Should not return closed nodes + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + const host = win.__slick.resetHost(); + host.innerHTML = 'foo'; + }); + }, + cases: [ + { byTag: '*', ref: { by: 'id', id: 'host' }, expect: { count: 0 } }, + ], + }, + + { + // querySelector Should start finding nodes from the passed context + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { id: 'queryselectorall', type: 'text' }); + }); + }, + cases: [ + { first: 'div #queryselectorall', ref: { by: 'id', id: 'host' }, expect: { count: 0 }, status: 'fixme' }, // probably legacy behavior + ], + }, + { + // querySelector Should not return a comment node with * selector + setupPage: async (page) => { + await page.evaluate(() => { + const host = (window as BugWin).__slick.resetHost(); + host.appendChild(document.createComment('')); + }); + }, + cases: [ + { first: '*', ref: { by: 'id', id: 'host' }, expect: { count: 0 } }, + ], + }, + { + // querySelector Should not return closed nodes + setupPage: async (page) => { + await page.evaluate(() => { + const host = (window as BugWin).__slick.resetHost(); + host.innerHTML = 'foo'; + }); + }, + cases: [ + { first: '*', ref: { by: 'id', id: 'host' }, expect: { count: 0 } }, + ], + }, + + { + // querySelectorAll Should start finding nodes from the passed context + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { id: 'queryselectorall', type: 'text' }); + }); + }, + cases: [ + { select: 'div #queryselectorall', ref: { by: 'id', id: 'host' }, expect: { count: 0 }, status: 'fixme' }, // probably legacy behavior + ], + }, + { + // querySelectorAll Should not return comment nodes with * selector + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + const host = win.__slick.resetHost(); + host.appendChild(document.createComment('')); + }); + }, + cases: [ + { select: '*', ref: { by: 'id', id: 'host' }, expect: { count: 0 } }, + ], + }, + { + // querySelectorAll Should not return closed nodes + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + const host = win.__slick.resetHost(); + host.innerHTML = 'foo'; + }); + }, + cases: [ + { select: '*', ref: { by: 'id', id: 'host' }, expect: { count: 0 } }, + ], + }, + + // Omitted from migration: XPath + // Reason: harness models CSS selectors, not legacy XPath DOM APIs. + + ], + } satisfies Scenario)), + + { + name: 'dojo/basic-selectors', + markup: ` + + + testing dojo.query() + + + + +

    testing dojo.query()

    +
    +

    h3 span endh3

    + +
    +

    h3

    + + +
    +

    h3

    +

    h3

    + + + + + +
    +
    +
    +
    +
    +
    + + +
    +
    + + + + + + +
    + + + +
    +
    +

    one

    +
    +

    two

    +
    +
    +
    + + + `, + markupMode: 'html-document', + cases: [ + // basic sanity checks + { select: 'h3', expect: { count: 4 } }, + { select: 'h1:first-child', expect: { count: 1 } }, + { select: 'h3:first-child', expect: { count: 2 } }, + { select: '#t', expect: { count: 1 } }, + { select: '#bug', expect: { count: 1 } }, + { select: '#t h3', expect: { count: 4 } }, + { select: 'div#t', expect: { count: 1 } }, + { select: 'div#t h3', expect: { count: 4 } }, + { select: 'span#t', expect: { count: 0 } }, + { select: '.bogus', expect: { count: 0 } }, + { select: '.bogus', ref: { by: 'id', id: 'container' }, expect: { count: 0 } }, + { select: '#bogus', expect: { count: 0 } }, + { select: '#bogus', ref: { by: 'id', id: 'container' }, expect: { count: 0 } }, + { select: '#t div > h3', expect: { count: 1 } }, + { select: '.foo', expect: { count: 2 } }, + { select: '.foo.bar', expect: { count: 1 } }, + { select: '.baz', expect: { count: 2 } }, + { select: '#t > h3', expect: { count: 3 } }, + + { select: '#baz,#foo,#t', expect: { count: 2 } }, + + // classnames aren't case sensitive, only attribute selectors and xml tagnames, this spec is invalid + // modified from `1` to `2` because the element classname property is case insensitive (dperini) + { select: '.fooBar', expect: { count: 2 } }, + + // modified from `1` to `2` because classes from the class attribute of HTML elements in documents + // that are in quirks mode must be treated as ASCII case-insensitive. (jddalton) + // document is not in quirks mode, tested compatMode to be CSS1Compat (dperini) + // http://www.whatwg.org/specs/web-apps/current-work/#selectors + { select: '[class~=foobar]', expect: { count: 1 } }, + { select: '[class~=fooBar]', expect: { count: 1 } }, + + // syntactic equivalents + { select: '#t > *', expect: { count: 12 } }, + { select: '.foo > *', expect: { count: 3 } }, + // { select: '#t >', expect: { count: 12 } }, + // { select: '.foo >', expect: { count: 3 } }, + + // with a root, by ID + { select: ':scope > *', ref: { by: 'id', id: 'container' }, expect: { count: 3 } }, + { select: ':scope > h3', ref: { by: 'id', id: 't' }, expect: { count: 3 } }, + + // compound queries + { select: '.foo, .bar', expect: { count: 2 } }, + { select: '.foo,.bar', expect: { count: 2 } }, + + // multiple class attribute + { select: '.foo.bar', expect: { count: 1 } }, + { select: '.foo', expect: { count: 2 } }, + { select: '.baz', expect: { count: 2 } }, + + // case sensitivity + { select: 'span.baz', expect: { count: 1 } }, + { select: 'sPaN.baz', expect: { count: 1 }, status: 'fixme' }, + { select: 'SPAN.baz', expect: { count: 1 }, status: 'fixme' }, + { select: '[class = "foo bar"]', expect: { count: 1 } }, + { select: '[foo~="bar"]', expect: { count: 2 } }, + { select: '[ foo ~= "bar" ]', expect: { count: 2 } }, + + { select: `[ foo ~= "'bar'" ]`, expect: { count: 0 } }, + { select: '[foo]', expect: { count: 3 } }, + { select: '[foo$="thud"]', expect: { count: 1 } }, + { select: '[foo$=thud]', expect: { count: 1 } }, + { select: '[foo$="thudish"]', expect: { count: 1 } }, + { select: '#t [foo$=thud]', expect: { count: 1 } }, + { select: '#t [ title $= thud ]', expect: { count: 1 } }, + { select: '#t span[ title $= thud ]', expect: { count: 0 } }, + + // Original expected 1, but this mock has two matching elements. + { select: '[foo|="bar"]', expect: { count: 2 } }, + + { select: '[foo|="bar-baz"]', expect: { count: 1 } }, + { select: '[foo|="baz"]', expect: { count: 0 } }, + + { select: '.foo:nth-child(2)', expect: { ids: ['_foo'] } }, + { first: ':nth-child(2)', expect: { equivalentCase: { first: 'style' } } }, + + // descendant selectors + // { select: ':scope >', ref: { by: 'id', id: 'container' }, expect: { count: 3 } }, + { select: ':scope > *', ref: { by: 'id', id: 'container' }, expect: { count: 3 } }, + { select: ':scope > [qux]', ref: { by: 'id', id: 'container' }, expect: { count: 2, ids: ['child1', 'child3'] } }, + + { select: '#bug', expect: { ids: ['bug'] } }, + + // bug 9071 + { select: 'a', ref: { by: 'id', id: 't4' }, expect: { count: 2 } }, + { select: 'p a', ref: { by: 'id', id: 't4' }, expect: { count: 2 } }, + { select: 'div p', ref: { by: 'id', id: 't4' }, expect: { count: 2 } }, + { select: 'div p a', ref: { by: 'id', id: 't4' }, expect: { count: 2 } }, + { select: '.subA', ref: { by: 'id', id: 't4' }, expect: { count: 2 } }, + { select: '.subP .subA', ref: { by: 'id', id: 't4' }, expect: { count: 2 } }, + { select: '.subDiv .subP', ref: { by: 'id', id: 't4' }, expect: { count: 2 } }, + { select: '.subDiv .subP .subA', ref: { by: 'id', id: 't4' }, expect: { count: 2 } }, + + // failed scope arg + { select: 'div#foo', expect: { count: 0 } }, + + // Removed as this is specific to Dojo API (jddalton) + // { select: '*', ref: { by: 'id', id: 'thinger' }, expect: { count: 0 } }, + + // sibling selectors + // { select: ':scope + *', ref: { by: 'id', id: 'container' }, expect: { count: 1 } }, + // { select: ':scope ~ *', ref: { by: 'id', id: 'container' }, expect: { count: 3 } }, + { select: '.foo + span', expect: { count: 1 } }, + { select: '.foo ~ span', expect: { count: 4 } }, + { select: '#foo ~ *', expect: { count: 1 } }, + // { select: '#foo ~', expect: { count: 1 } }, + + // sub-selector parsing + { select: '#t span.foo:not(span:first-child)', expect: { count: 1 } }, + { select: '#t span.foo:not(:first-child)', expect: { count: 1 } }, + + // nth-child tests + { select: '#t > h3:nth-child(odd)', expect: { count: 2 } }, + { select: '#t h3:nth-child(odd)', expect: { count: 3 } }, + { select: '#t h3:nth-child(2n+1)', expect: { count: 3 } }, + { select: '#t h3:nth-child(even)', expect: { count: 1 } }, + { select: '#t h3:nth-child(2n)', expect: { count: 1 } }, + { select: '#t h3:nth-child(2n+3)', expect: { count: 1 } }, + { select: '#t h3:nth-child(1)', expect: { count: 2 } }, + { select: '#t > h3:nth-child(1)', expect: { count: 1 } }, + { select: '#t :nth-child(3)', expect: { count: 3 } }, + { select: '#t > div:nth-child(1)', expect: { count: 0 } }, + { select: '#t span', expect: { count: 7 } }, + { select: '#t > *:nth-child(n+10)', expect: { count: 3 } }, + { select: '#t > *:nth-child(n+12)', expect: { count: 1 } }, + { select: '#t > *:nth-child(-n+10)', expect: { count: 10 } }, + { select: '#t > *:nth-child(-2n+10)', expect: { count: 5 } }, + { select: '#t > *:nth-child(2n+2)', expect: { count: 6 } }, + { select: '#t > *:nth-child(2n+4)', expect: { count: 5 } }, + { select: '#t > *:nth-child(2n+4)', expect: { count: 5 } }, + { select: '#t > *:nth-child(n-5)', expect: { count: 12 } }, + { select: '#t > *:nth-child(2n-5)', expect: { count: 6 } }, + + // :checked pseudo-selector + { select: '#t2 > :checked', expect: { count: 2 } }, + { first: '#t2 > input[type=checkbox]:checked', expect: { ids: ['checkbox2'] } }, + { first: '#t2 > input[type=radio]:checked', expect: { ids: ['radio2'] } }, + { select: '#t2select option:checked', expect: { count: 2 } }, + + // :empty pseudo-selector + { select: '#t > span:empty', expect: { count: 4 } }, + { select: '#t span:empty', expect: { count: 6 } }, + { select: 'h3 span:empty', expect: { count: 0 } }, + { select: 'h3 :not(:empty)', expect: { count: 1 } }, + + // escaping of ":" chars inside an ID + { byId: 'silly:id::with:colons', expect: { count: 1 } }, + { select: '#silly\\:id\\:\\:with\\:colons', expect: { count: 1 } }, + ], + }, + + { + name: 'dojo/cross-document-query', + markupMode: 'html-document', + markup: ` + + `, + cases: [ + { select: 'h3', ref: { by: 'id', id: 'st1', within: { by: 'iframe', id: 't3' } }, expect: { count: 1 } }, + + // use a long query to force a test of the XPath system on FF. see bug #7075 + { select: 'h3 > span > span > span', ref: { by: 'id', id: 'st1', within: { by: 'iframe', id: 't3' } }, expect: { count: 1 } }, + + { select: 'h3 > span > span > span', ref: { by: 'first', selector: 'body > *', within: { by: 'iframe', id: 't3' } }, expect: { count: 1 } }, + ], + }, + + { + name: 'dojo/xml-case-sensitivity', + markupMode: 'xml-document', + markup: ` + + One + Two + Three + Four + + `, + cases: [ + { select: 'result', expect: { count: 2 } }, + { select: 'Result', expect: { count: 1 } }, + { select: 'RESULT', expect: { count: 1 } }, + { select: 'resulT', expect: { count: 0 } }, + { select: 'rEsulT', expect: { count: 0 } }, + ], + }, + + { + name: 'dojo/xml-attrs', + markupMode: 'xml-document', + markup: ` + + Two + Two + + `, + cases: [ + { select: 'RESULT', expect: { count: 2 } }, + { select: 'RESULT[THINGER]', expect: { count: 0 } }, + { select: 'RESULT[thinger]', expect: { count: 2 } }, + { select: 'RESULT[thinger=blah]', expect: { count: 1 } }, + ], + }, + + ...allTemplates.map(([name, markup]) => ( + { + name: `engine-bugs/${name}`, + markup, + markupMode: name === 'xml' || name === 'svg' ? 'xml-document' : 'html-document', + setupPage: async (page) => { + await initPage(page, name); + }, + steps: [ + { + // 1) document should have a documentElement / should have nodes + cases: [ + { select: '*', ref: { by: 'documentElement' } }, + { byTag: '*' }, + { select: '*' }, + ], + }, + { + // 2) Malformed closing markup should not produce divergent * results + setupPage: async (page) => { + await page.evaluate((n) => { + const win = window as BugWin; + const isXmlLike = n === 'xml' || n === 'svg'; + + win.__slick.resetHost(); + + // can't set innerHTML to malformed markup in XML documents, so can only test html-like docs + if (!isXmlLike) { + win.__slick.setHostHTML('foo'); + } + }, name); + }, + cases: [ + { select: '*', ref: { by: 'id', id: 'host' } }, + { byTag: '*', ref: { by: 'id', id: 'host' } }, + ], + }, + { + // 3) Broad traversal should stay equivalent + // * should not surface comment nodes as selected elements + cases: [ + { select: '*' }, + { byTag: '*' }, + ], + }, + + { + // 4) Selecting by the second class should still match + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('span', { class: 'class1 class2', className: 'class1 class2' }); + }); + }, + cases: [ + { select: '.class2', ref: { by: 'id', id: 'host' }, expect: { count: 1 } }, + { byClass: 'class2', ref: { by: 'id', id: 'host' }, expect: { count: 1 } }, + ], + }, + + // Class matching should track attribute removal and re-assignment + { + // 5) Initial state: two .b nodes + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('span', { id: 'tmpNode1', class: 'b', className: 'b' }); + win.__slick.add('span', { id: 'tmpNode2', class: 'b', className: 'b' }); + }); + }, + cases: [ + { select: '.b', ref: { by: 'id', id: 'host' }, expect: { count: 2 } }, + { byClass: 'b', ref: { by: 'id', id: 'host' }, expect: { count: 2 } }, + { select: '.f', ref: { by: 'id', id: 'host' }, expect: { count: 0 } }, + { byClass: 'f', ref: { by: 'id', id: 'host' }, expect: { count: 0 } }, + { select: '[class|=b]', ref: { by: 'id', id: 'host' }, expect: { count: 2 } }, + { select: '[class=b]', ref: { by: 'id', id: 'host' }, expect: { count: 2 } }, + ], + }, + { + // 6) After changing tmpNode1 from .b to .f + setupPage: async (page) => { + await page.evaluate(() => { + const node = document.getElementById('tmpNode1'); + if (!node) throw new Error('tmpNode1 not found'); + node.removeAttribute('class'); + node.removeAttribute('className'); + node.setAttribute('class', 'f'); + node.setAttribute('className', 'f'); + }); + }, + cases: [ + { select: '.b', ref: { by: 'id', id: 'tmpNode1' }, expect: { count: 0 } }, + { byClass: 'b', ref: { by: 'id', id: 'tmpNode1' }, expect: { count: 0 } }, + { select: '.b', ref: { by: 'id', id: 'host' }, expect: { count: 1 } }, + { byClass: 'b', ref: { by: 'id', id: 'host' }, expect: { count: 1 } }, + { select: '.f', ref: { by: 'id', id: 'host' }, expect: { count: 1 } }, + { byClass: 'f', ref: { by: 'id', id: 'host' }, expect: { count: 1 } }, + ], + }, + { + // 7) After changing tmpNode1 back from .f to .b + setupPage: async (page) => { + await page.evaluate(() => { + const node = document.getElementById('tmpNode1'); + if (!node) throw new Error('tmpNode1 not found'); + node.removeAttribute('class'); + node.removeAttribute('className'); + node.setAttribute('class', 'b'); + node.setAttribute('className', 'b'); + }); + }, + cases: [ + { select: '.b', ref: { by: 'id', id: 'host' }, expect: { count: 2 } }, + { byClass: 'b', ref: { by: 'id', id: 'host' }, expect: { count: 2 } }, + { select: '.f', ref: { by: 'id', id: 'host' }, expect: { count: 0 } }, + { byClass: 'f', ref: { by: 'id', id: 'host' }, expect: { count: 0 } }, + ], + }, + + { + // 8) Detached context subtree should still support id selection within itself + setupPage: async (page) => { + const mismatch = await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { id: 'someuniqueid', type: 'text' }); + + const host = win.__slick.getHost(); + host.remove(); + + const native = [...host.querySelectorAll('#someuniqueid')]; + const nw = NW.Dom.select('#someuniqueid', host); + + const same = native.length === nw.length && native.every((el, i) => el === nw[i]); + if (!same) return `Detached query mismatch: native=${native.length}, nw=${nw.length}`; + return undefined; + }); + + expect(mismatch).toBeUndefined(); + }, + cases: [], + }, + + + // [name=...] should match the name attribute, not a sibling id with the same value + { + // id-first, then name + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { id: 'getelementsbyname', type: 'password' }); + win.__slick.add('input', { id: 'tmpNode1', name: 'getelementsbyname', type: 'text' }); + }); + }, + cases: [ + { select: '[name=getelementsbyname]', ref: { by: 'id', id: 'host' }, expect: { count: 1 } }, + ], + }, + { + // name-first, then id + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { id: 'tmpNode1', name: 'getelementsbyname', type: 'text' }); + win.__slick.add('input', { id: 'getelementsbyname', type: 'password' }); + }); + }, + cases: [ + { select: '[name=getelementsbyname]', ref: { by: 'id', id: 'host' }, expect: { count: 1 } }, + ], + }, + + // [name=...] should not match a sibling id with the same value + { + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { id: 'getelementsbyname', type: 'password', class: 'tmpNode2' }); + win.__slick.add('input', { name: 'getelementsbyname', type: 'text', class: 'tmpNode1' }); + }); + }, + cases: [ + { select: '[name=getelementsbyname]', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode1'] } }, + ], + }, + { + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { name: 'getelementsbyname', type: 'text', class: 'tmpNode1' }); + win.__slick.add('input', { id: 'getelementsbyname', type: 'password', class: 'tmpNode2' }); + }); + }, + cases: [ + { select: '[name=getelementsbyname]', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode1'] } }, + ], + }, + + // Should NOT match name attribute + { + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { name: 'getelementbyid', type: 'text', class: 'tmpNode1' }); + win.__slick.add('input', { id: 'getelementbyid', type: 'password', class: 'tmpNode2' }); + }); + }, + cases: [ + { select: '#getelementbyid', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode2'] } }, + { byId: 'getelementbyid', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode2'] } }, + ], + }, + + // Should NOT match name attribute, using innerHTML + { + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + const host = win.__slick.resetHost(); + host.innerHTML = ''; + }); + }, + cases: [ + { select: '#getelementbyid', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode2'] } }, + { byId: 'getelementbyid', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode2'] } }, + ], + }, + + // Should match id attribute, even when another element has that [name] + { + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { name: 'getelementbyid', type: 'text', class: 'tmpNode1' }); + win.__slick.add('input', { id: 'getelementbyid', type: 'password', class: 'tmpNode2' }); + win.__slick.add('input', { name: 'getelementbyid', type: 'text', class: 'tmpNode3' }); + }); + }, + cases: [ + { select: '#getelementbyid', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode2'] } }, + { byId: 'getelementbyid', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode2'] } }, + ], + }, + + + // Should match id attribute, even when another element has that [name], using innerHTML + { + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { name: 'getelementbyid', type: 'text', class: 'tmpNode1' }); + win.__slick.add('input', { id: 'getelementbyid', type: 'password', class: 'tmpNode2' }); + win.__slick.add('input', { name: 'getelementbyid', type: 'text', class: 'tmpNode3' }); + }); + }, + cases: [ + { select: '#getelementbyid', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode2'] } }, + { byId: 'getelementbyid', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode2'] } }, + ], + }, + + // Should get just the first matched element with passed id, using innerHTML + { + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { name: 'getelementbyid', type: 'text', class: 'tmpNode1' }); + win.__slick.add('input', { id: 'getelementbyid', type: 'password', class: 'tmpNode2' }); + win.__slick.add('input', { name: 'getelementbyid', type: 'text', class: 'tmpNode3' }); + win.__slick.add('input', { id: 'getelementbyid', type: 'text', class: 'tmpNode4' }); + }); + }, + cases: [ + { select: '#getelementbyid', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode2', 'tmpNode4'], count: 2 } }, + { byId: 'getelementbyid', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode2', 'tmpNode4'], count: 2 }, status: 'fixme' }, + ], + }, + + // Should get just the first matched element with passed id, using innerHTML, changing nodes orders + { + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + win.__slick.add('input', { id: 'getelementbyid', type: 'password', class: 'tmpNode1' }); + win.__slick.add('input', { name: 'getelementbyid', type: 'text', class: 'tmpNode2' }); + win.__slick.add('input', { name: 'getelementbyid', type: 'text', class: 'tmpNode3' }); + win.__slick.add('input', { id: 'getelementbyid', type: 'text', class: 'tmpNode4' }); + }); + }, + cases: [ + { select: '#getelementbyid', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode1'], count: 1 }, status: 'fail' }, // legacy is wrong.. + { byId: 'getelementbyid', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode1'], count: 1 }, status: 'fixme' }, // mismatch + ], + }, + + // Should match the selected option + { + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + const sel = win.__slick.add('select'); + win.__slick.add('option', { value: '1', class: 'tmpNode2' }, sel).textContent = 'opt1'; + win.__slick.add('option', { value: '2', class: 'tmpNode3' }, sel).textContent = 'opt2'; + }); + }, + cases: [ + { select: ':selected', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode2'], count: 1 }, status: 'skip' }, // unsupported + ], + }, + + // Should not match the first element from a multiple select + { + setupPage: async (page) => { + await page.evaluate(() => { + const win = window as BugWin; + win.__slick.resetHost(); + const sel = win.__slick.add('select', { multiple: 'multiple' }); + win.__slick.add('option', { value: '1', class: 'tmpNode2' }, sel).textContent = 'opt1'; + win.__slick.add('option', { value: '2', selected: 'selected', class: 'tmpNode3' }, sel).textContent = 'opt2'; + }); + }, + cases: [ + { select: ':selected', ref: { by: 'id', id: 'host' }, expect: { classes: ['tmpNode3'], count: 1 }, status: 'skip' }, // unsupported + ], + }, + ], + + } satisfies Scenario)), + + { + name: 'google_closure', + markupMode: 'html-document', + markup: ` + + + + Closure Unit Tests - goog.dom + + +

    testing goog.dom.query()

    +
    +

    h3 span endh3

    + +
    +

    h3

    + + +
    +

    h3

    +

    h3

    + + + + + +
    +
    +
    +
    +
    +
    + + +
    + +
    + + + + + + +
    + + +
    +
    +
    +
    +
    +
    +
    + + + + `, + cases: [ + // testBasicSelectors + { select: 'h3', expect: { count: 4 } }, + { select: 'h1:first-child', expect: { count: 1 } }, + { select: 'h3:first-child', expect: { count: 2 } }, + { select: '#t', expect: { count: 1 } }, + { select: '#bug', expect: { count: 1 } }, + { select: '#t h3', expect: { count: 4 } }, + { select: 'div#t', expect: { count: 1 } }, + { select: 'div#t h3', expect: { count: 4 } }, + { select: 'span#t', expect: { count: 0 } }, + { select: '#t div > h3', expect: { count: 1 } }, + { select: '.foo', expect: { count: 2 } }, + { select: '.foo.bar', expect: { count: 1 } }, + { select: '.baz', expect: { count: 2 } }, + { select: '#t > h3', expect: { count: 3 } }, + + // testSyntacticEquivalents + { select: '#t > *', expect: { count: 12 } }, + { select: '#t >', expect: { throws: true } }, + { select: '.foo > *', expect: { count: 3 } }, + { select: '.foo >', expect: { throws: true } }, + + // testWithARootById + { select: ':scope > *', ref: { by: 'id', id: 'container' }, expect: { count: 3 } }, + { select: ':scope > h3', ref: { by: 'id', id: 't' }, expect: { count: 3 } }, + + // testCompoundQueries + { select: '.foo, .bar', expect: { count: 2 } }, + { select: '.foo,.bar', expect: { count: 2 } }, + + // testMultipleClassAttributes + { select: '.foo.bar', expect: { count: 1 } }, + { select: '.foo', expect: { count: 2 } }, + { select: '.baz', expect: { count: 2 } }, + + // testCaseSensitivity + { select: 'span.baz', expect: { count: 1 } }, + { select: 'sPaN.baz', expect: { count: 1 }, status: 'fixme' }, + { select: 'SPAN.baz', expect: { count: 1 }, status: 'fixme' }, + { select: '[class = "foo bar"]', expect: { count: 1 } }, + { select: '[foo~="bar"]', expect: { count: 2 } }, + { select: '[ foo ~= "bar" ]', expect: { count: 2 } }, + + // testAttributes + { select: '[foo]', expect: { count: 3 } }, + { select: '[foo$="thud"]', expect: { count: 1 } }, + { select: '[foo$=thud]', expect: { count: 1 } }, + { select: '[foo$="thudish"]', expect: { count: 1 } }, + { select: '#t [foo$=thud]', expect: { count: 1 } }, + { select: '#t [ title $= thud ]', expect: { count: 1 } }, + { select: '#t span[ title $= thud ]', expect: { count: 0 } }, + { select: '[foo|="bar"]', expect: { count: 2 } }, + { select: '[foo|="bar-baz"]', expect: { count: 1 } }, + { select: '[foo|="baz"]', expect: { count: 0 } }, + + // testDescendantSelectors + { select: '>', ref: { by: 'id', id: 'container' }, expect: { throws: true } }, + { select: ':scope > *', ref: { by: 'id', id: 'container' }, expect: { count: 3 } }, + { select: ':scope > [qux]', ref: { by: 'id', id: 'container' }, expect: { count: 2, ids: ['child1', 'child3'] } }, + + // testSiblingSelectors + { select: '+', expect: { throws: true } }, + { select: '~', expect: { throws: true } }, + { select: '.foo + span', expect: { count: 1 } }, + { select: '.foo ~ span', expect: { count: 4 } }, + { select: '#foo ~ *', expect: { count: 1 } }, + { select: '#foo ~', expect: { throws: true } }, + + // testSubSelectors + { select: '#t span.foo:not(span:first-child)', expect: { count: 1 } }, + { select: '#t span.foo:not(:first-child)', expect: { count: 1 } }, + + // testNthChild + { select: '.foo:nth-child(2)', expect: { ids: ['_foo'] } }, + { select: '#t > h3:nth-child(odd)', expect: { count: 2 } }, + { select: '#t h3:nth-child(odd)', expect: { count: 3 } }, + { select: '#t h3:nth-child(2n+1)', expect: { count: 3 } }, + { select: '#t h3:nth-child(even)', expect: { count: 1 } }, + { select: '#t h3:nth-child(2n)', expect: { count: 1 } }, + { select: '#t h3:nth-child(2n+3)', expect: { count: 1 } }, + { select: '#t h3:nth-child(1)', expect: { count: 2 } }, + { select: '#t > h3:nth-child(1)', expect: { count: 1 } }, + { select: '#t :nth-child(3)', expect: { count: 3 } }, + { select: '#t > div:nth-child(1)', expect: { count: 0 } }, + { select: '#t span', expect: { count: 7 } }, + { select: '#t > *:nth-child(n+10)', expect: { count: 3 } }, + { select: '#t > *:nth-child(n+12)', expect: { count: 1 } }, + { select: '#t > *:nth-child(-n+10)', expect: { count: 10 } }, + { select: '#t > *:nth-child(-2n+10)', expect: { count: 5 } }, + { select: '#t > *:nth-child(2n+2)', expect: { count: 6 } }, + { select: '#t > *:nth-child(2n+4)', expect: { count: 5 } }, + { select: '#t > *:nth-child(2n+4)', expect: { count: 5 } }, + { select: '#t > *:nth-child(n-5)', expect: { count: 12 } }, + { select: '#t > *:nth-child(2n-5)', expect: { count: 6 } }, + + // testEmptyPseudoSelector + { select: '#t > span:empty', expect: { count: 4 } }, + { select: '#t span:empty', expect: { count: 6 } }, + { select: 'h3 span:empty', expect: { count: 0 } }, + { select: 'h3 :not(:empty)', expect: { count: 1 } }, + + // testIdsWithColons + { select: "[id = 'silly:id::with:colons']", expect: { count: 1 } }, + { select: '#silly\\:id\\:\\:with\\:colons', expect: { count: 1 } }, + + // testOrder + { select: '.myupperclass .myclass input', expect: { ids: ['myid1', 'myid2'], count: 2 } }, + ], + steps: [ + // testCorrectDocumentInFrame + { + setupPage: async (page) => { + await page.evaluate(() => { + const frameDocument = (window.frames as any)['ifr'].document; + if (!frameDocument) throw new Error('frame document not found'); + const src = document.getElementById('iframe-test'); + if (!src) throw new Error('#iframe-test not found'); + frameDocument.body.innerHTML = src.innerHTML; + }); + }, + cases: [ + { select: '#if1 .if2 div', ref: { by: 'iframe', id: 'ifrid' }, expect: { ids: ['if3'], count: 1 } }, + { select: '#if1 .if2 div', ref: { by: 'id', id: 'iframe-test' }, expect: { ids: ['if3'], count: 1 } }, + { + select: '#if1 .if2 div', ref: { by: 'id', id: 'iframe-test' }, + expect: { equivalentCase: { select: '#if1 .if2 div', ref: { by: 'iframe', id: 'ifrid' } } }, + status: 'fail', + }, + ], + }, + ], + }, + + { + name: 'slick_html', + markupMode: 'html-document', + markup: ` + + + + + Mootools Query Test + + + some + some + some +
    some
    +
    some
    +
    some
    + +
    text
    +
    + + + `, + cases: [ + // Slick + { select: 'body a[tabindex="0"]', expect: { ids: ['atabindex0'], count: 1 } }, + { first: 'body a[tabindex="0"]', expect: { ids: ['atabindex0'], count: 1 } }, + { match: 'body a[tabindex="0"]', ref: { by: 'id', id: 'atabindex0' }, expect: { ids: ['atabindex0'], count: 1 } }, + + { select: 'body a[tabindex="1"]', expect: { ids: ['atabindex1'], count: 1 } }, + { first: 'body a[tabindex="1"]', expect: { ids: ['atabindex1'], count: 1 } }, + { match: 'body a[tabindex="1"]', ref: { by: 'id', id: 'atabindex1' }, expect: { ids: ['atabindex1'], count: 1 } }, + + { select: 'body a[tabindex]', expect: { ids: ['atabindex0', 'atabindex1'], count: 2 } }, + { first: 'body a[tabindex]', expect: { ids: ['atabindex0'], count: 1 } }, + { match: 'body a[tabindex]', ref: { by: 'id', id: 'atabindex0' }, expect: { ids: ['atabindex0'], count: 1 } }, + + { select: 'body [tabindex="0"]', expect: { ids: ['atabindex0', 'divtabindex0'], count: 2 } }, + { first: 'body [tabindex="0"]', expect: { ids: ['atabindex0'], count: 1 } }, + { match: 'body [tabindex="0"]', ref: { by: 'id', id: 'atabindex0' }, expect: { ids: ['atabindex0'], count: 1 } }, + + { select: 'body [tabindex="1"]', expect: { ids: ['atabindex1', 'divtabindex1'], count: 2 } }, + { first: 'body [tabindex="1"]', expect: { ids: ['atabindex1'], count: 1 } }, + { match: 'body [tabindex="1"]', ref: { by: 'id', id: 'atabindex1' }, expect: { ids: ['atabindex1'], count: 1 } }, + + { select: 'body [tabindex]', expect: { ids: ['atabindex0', 'atabindex1', 'divtabindex0', 'divtabindex1'], count: 4 } }, + { first: 'body [tabindex]', expect: { ids: ['atabindex0'], count: 1 } }, + { match: 'body [tabindex]', ref: { by: 'id', id: 'atabindex0' }, expect: { ids: ['atabindex0'], count: 1 } }, + + // Combinators + { select: '#one ~ *', expect: { count: 1 } }, + { select: '#one ~ div', expect: { count: 1 } }, + { select: '#one > i', expect: { count: 1 } }, + { select: '#one + *', expect: { count: 1 } }, + { select: '#one + div', expect: { count: 1 } }, + + { select: ':scope ~ *', ref: { by: 'id', id: 'one' }, expect: { count: 0 } }, + { select: ':scope ~ div', ref: { by: 'id', id: 'one' }, expect: { count: 0 } }, + { select: ':scope > i', ref: { by: 'id', id: 'one' }, expect: { count: 1 } }, + { select: ':scope + *', ref: { by: 'id', id: 'one' }, expect: { count: 0 } }, + { select: ':scope + div', ref: { by: 'id', id: 'one' }, expect: { count: 0 } }, + ], + }, + + + { + name: 'html5', + markupMode: 'html-document', + markup: ` + + + + HTML 5 Reference + + + +
    +
    +

    Hi

    + +
    +
    + + + +
    +

    Abstract

    + +

    This document illustrates how to write HTML 5 documents, focussing on + simplicity and practical applications for beginners while also providing + in depth information for more advanced web developers.

    +
    + + +
    +

    Status of this document

    +

    This section describes the status of this document at the time of its + publication. Other documents may supersede this document. A list of + current W3C publications and the latest revision of this technical report + can be found in the W3C technical reports + index at http://www.w3.org/TR/.

    + +

    This document is an Editors Draft of the “HTML 5 Reference” + produced by the HTML Working Group, + part of the HTML Activity. + The working group is working on HTML 5 (see the + HTML 5 Editor's draft). + The appropriate forum for comments on this document is + public-html-comments@w3.org + (public archive) + or public-html@w3.org + + (public archive).

    + +

    Publication as a Working Group Note does not imply endorsement by the W3C + Membership. This is a draft document and may be updated, replaced or + obsoleted by other documents at any time. It is inappropriate to cite + this document as other than work in progress.

    + +

    This document was produced by a group operating under the + 5 February 2004 W3C Patent Policy. + W3C maintains a public list of any patent disclosures + made in connection with the deliverables of the group; that page also + includes instructions for disclosing a patent. An individual who has + actual knowledge of a patent which the individual believes contains + Essential Claim(s) + + must disclose the information in accordance with + section 6 of the W3C Patent Policy.

    +
    + + + + `, + cases: [ + // HTML5 new tags + + { select: 'section', expect: { count: 2 } }, + { first: 'section' }, + { match: 'section', ref: { by: 'id', id: 'abstract' } }, + + { select: '#page header nav', expect: { count: 1 } }, + { first: '#page header nav', expect: { count: 1 } }, + { match: '#page header nav', ref: { by: 'first', selector: '#page header nav' }, expect: { count: 1 } }, + + { select: 'header[role="banner"]', expect: { count: 1 } }, + { first: 'header[role="banner"]', expect: { count: 1 } }, + { match: 'header[role="banner"]', ref: { by: 'first', selector: 'header[role="banner"]' }, expect: { count: 1 } }, + + { select: 'input[type="search"]', expect: { count: 1 } }, + { first: 'input[type="search"]', expect: { count: 1 } }, + { match: 'input[type="search"]', ref: { by: 'first', selector: 'input[type="search"]' }, expect: { count: 1 } }, + ], + }, + + ...xmlTemplates.map(([name, markup]) => ({ + name: `isXml/${name}`, + markup, + markupMode: 'xml-document', + setupPage: async (page) => { + const result = await page.evaluate(() => { + const legacyIsXML = (element: Document | Element) => { + const ownerDocument = element.ownerDocument || element; + return !('body' in ownerDocument) || + !('innerHTML' in ownerDocument.documentElement) || + ownerDocument.createElement('DiV').nodeName === 'DiV'; + }; + + return { + nodeType: document.nodeType, + // isGlobalDoc: document === window.document, + isXml: legacyIsXML(document), + }; + }); + + expect(result.nodeType).toBe(9); + // expect(result.isGlobalDoc).toBe(false); + expect(result.isXml).toBe(true); + }, + } satisfies Scenario)), + + ...htmlTemplates.map(([name, markup]) => ({ + name: `isNotXml/${name}`, + markup, + markupMode: 'html-document', + setupPage: async (page) => { + const result = await page.evaluate(() => { + const legacyIsXML = (element: Document | Element) => { + const ownerDocument = element.ownerDocument || element; + return !('body' in ownerDocument) || + !('innerHTML' in ownerDocument.documentElement) || + ownerDocument.createElement('DiV').nodeName === 'DiV'; + }; + + return { + nodeType: document.nodeType, + // isGlobalDoc: document === window.document, + isXml: legacyIsXML(document), + }; + }); + + expect(result.nodeType).toBe(9); + // expect(result.isGlobalDoc).toBe(false); + expect(result.isXml).toBe(false); + }, + } satisfies Scenario)), + + { + name: 'match/basic-empty-string', + markupMode: 'html-body', + markup: `
    `, + cases: [ + { match: '', ref: { by: 'id', id: 'testNode' }, expect: { throws: true } }, + ], + }, + + { + name: 'match/attributes', + markupMode: 'html-body', + markup: ` +
    +
    +
    + `, + cases: [ + { select: `[attr='test you!']`, expect: { ids: ['test1'] } }, + { select: `[attr='test me!']`, expect: { ids: [] } }, + + { select: `[attr^='test']`, expect: { ids: ['test1', 'test2'] } }, + { select: `[attr^=' test']`, expect: { ids: [] } }, + + { select: `[attr$='you!']`, expect: { ids: ['test1', 'test3'] } }, + { select: `[attr$='you! ']`, expect: { ids: [] } }, + + { match: `[attr='test you!']`, ref: { by: 'id', id: 'test1' }, expect: { ids: ['test1'] } }, + { match: `[attr='test me!']`, ref: { by: 'id', id: 'test1' }, expect: { ids: [] } }, + + { match: `[attr^='test']`, ref: { by: 'id', id: 'test2' }, expect: { ids: ['test2'] } }, + { match: `[attr^=' test']`, ref: { by: 'id', id: 'test2' }, expect: { ids: [] } }, + + { match: `[attr$='you!']`, ref: { by: 'id', id: 'test3' }, expect: { ids: ['test3'] } }, + { match: `[attr$='you! ']`, ref: { by: 'id', id: 'test3' }, expect: { ids: [] } }, + ], + }, + + { + name: 'match/deep', + markupMode: 'html-body', + markup: ` +
    + + lorem + + + + lorem + + +
    + `, + cases: [ + { match: '*', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: ['a_tag1'] } }, + { match: 'a', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: ['a_tag1'] } }, + { match: ':not(a)', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: [] } }, + { match: 'del', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: [] } }, + { match: ':not(del)', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: ['a_tag1'] } }, + { match: '[id]', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: ['a_tag1'] } }, + { match: ':not([id])', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: [] } }, + { match: '[class]', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: ['a_tag1'] } }, + { match: ':not([class])', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: [] } }, + { match: '.a', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: ['a_tag1'] } }, + { match: ':not(.a)', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: [] } }, + + { match: '* *', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: ['a_tag1'] } }, + { match: '* > *', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: ['a_tag1'] } }, + { match: '* ~ *', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: [] } }, + { match: '* + *', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: [] } }, + { match: 'b a', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: ['a_tag1'] } }, + { match: 'b > a', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: ['a_tag1'] } }, + { match: 'div > b > a', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: ['a_tag1'] } }, + { match: 'div > b + b > a', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: ['a_tag1'] } }, + { match: 'div > b ~ b > a', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: ['a_tag1'] } }, + { match: 'div a', ref: { by: 'id', id: 'a_tag1' }, expect: { ids: ['a_tag1'] } }, + ], + }, + + + ...htmlTemplates.map(([name, markup]) => ({ + name: `mockTemplates/${name}`, + markup, + markupMode: 'html-document', + cases: [ + ...triFind(1, 'html'), + ...triFind(1, 'body'), + + // removes 'tel:' 'a' tags that are just grabbed by iphone + ...triFind(1814, 'body *:not([href^="tel:"])'), + + ...triFind(1, 'html'), + ...triFind(1, 'body'), + ...triFind(1, 'head'), + ...triFind(59, 'div'), + + ...triFind(43, '.example'), + ...triFind(14, '.note'), + ...triFind(5, '.fn'), + + ...triFind(4, '.a1'), + ...triFind(2, '.a1 .a1'), + ...triFind(2, '.a1 .a1'), + ...triFind(2, '.a1 > .a1'), + ...triFind(0, '.a1 + .a1'), + + ...triFind(12, '.a1 *'), + ...triFind(3, '.a1 > *'), + ...triFind(2, '.a1 + *'), + ...triFind(6, '.a1 ~ *'), + + // Remove custom selectors (jddalton) + // .a1 ! * / !> / !+ / !~ are old Slick custom combinators; skipped here. + + ...triFind(4, '.a4'), + ...triFind(2, '.a4 .a4'), + ...triFind(2, '.a4 > .a4'), + ...triFind(0, '.a4 + .a4'), + + ...triFind(324, 'body [class]:not([href^="tel:"])'), + ...triFind(13, 'body [title]:not([href^="tel:"])'), + ...triFind(1490, 'body :not([class]):not([href^="tel:"])'), + ...triFind(1801, 'body :not([title]):not([href^="tel:"])'), + + ...triFind(59, 'body div'), + + ...triFind(140, 'div p'), + ...triFind(140, 'div p'), + + ...triFind(134, 'div > p'), + ...triFind(22, 'div + p'), + ...triFind(183, 'div ~ p'), + + // subContext = third div, i.e. first `div.example` + { select: 'p', ref: { by: 'first', selector: 'div.example' }, expect: { count: 3 } }, + { select: ':scope > *', ref: { by: 'first', selector: 'div.example' }, expect: { count: 5 } }, + { select: ':scope > p', ref: { by: 'first', selector: 'div.example' }, expect: { count: 3 } }, + // { select: '+ *', expect: { count: 1 } }, + // { select: '+ p', expect: { count: 2 } }, + // { select: '~ *', expect: { count: 281 } }, + // { select: '~ p', expect: { count: 152 } }, + + ...triFind(43, 'div[class^=exa][class$=mple]'), + ...triFind(12, 'div p a:not([href^="tel:"])'), + ...triFind(683, 'div,p,a:not([href^="tel:"])'), + + ...triFind(43, 'DIV.example', 'fixme'), + ...triFind(43, 'DiV.example', 'fixme'), + ...triFind(12, 'ul .tocline2'), + ...triFind(44, 'div.example,div.note'), + + ...triFind(1, '#title'), + ...triFind(0, '#theres_no_such_id'), + ...triFind(1, 'h1#title'), + ...triFind(1, 'body #title'), + + ...triFind(12, 'ul.toc li.tocline2'), + ...triFind(12, 'ul.toc > li.tocline2'), + ...triFind(0, 'h1#title + div > p'), + + // pseudos + ...triFind(16, 'div:not(.example)'), + ...triFind(158, 'p:nth-child(even)'), + ...triFind(158, 'p:nth-child(2n)'), + ...triFind(166, 'p:nth-child(odd)'), + ...triFind(166, 'p:nth-child(2n+1)'), + ...triFind(324, 'p:nth-child(n)'), + ...triFind(3, 'p:only-child'), + ...triFind(19, 'p:last-child'), + ...triFind(54, 'p:first-child'), + + ...triFind(1, ':root'), + ...triFind(1, 'html:root > head:first-child'), + ...triFind(0, 'body:root'), + + // Remove custom selector (jddalton) + // `a ! :root` is an old Slick custom selector/combinator; skipped here. + + ...triFind(12, ':root ul .tocline2'), + ...triFind(0, 'body :root'), + + // `:contains(...)` is a nonstandard/custom selector; skipped here. + + ...triFind(1, '[href][lang][class]'), + ...triFind(324, '[class]'), + + ...triFind(43, '[class=example]'), + ...triFind(43, '[class^=exa]'), + ...triFind(44, '[class$=mple]'), + + // Remove invalid selectors (jddalton) + // `[class^=]`, `[class$=]`, `[class*=]` are invalid; skipped here. + + ...triFind(0, '[class^=""]'), + ...triFind(0, '[class$=""]'), + ...triFind(0, '[class*=""]'), + + ...triFind(1, '[lang|=tr]'), + ...triFind(324, '[class][class!=made_up]', 'skip'), // `!=` isn't supported + ...triFind(43, '[class~=example]'), + ], + + } satisfies Scenario)), + + + ...allTemplates.map(([name, markup]) => ({ + name: `selectExhaustive/${name}`, + status: name === 'html-quirks' ? 'fixme' : 'normal', + markup, + markupMode: name === 'xhtml' || name === 'xml' || name === 'svg' ? 'xml-document' : 'html-document', + setupPage: async (page) => { + await initPage(page, name); + await page.evaluate((n) => { + const win = window as BugWin; + + const CLASSES = [ + 'normal', + 'escaped,character', + 'ǝpoɔıun', + '瀡', + 'with-dash', + 'with_underscore', + 'number123', + 'MiXeDcAsE', + ]; + + win.__slick.resetHost(); + win.__slick.add('div', { id: 'all-classes', class: CLASSES.join(' ') }); + CLASSES.forEach((cls, i) => { + win.__slick.add('div', { id: `single-${i}`, class: cls }); + win.__slick.add('div', { id: `second-${i}`, class: `dummy ${cls}` }); + }); + }, name); + }, + cases: [ + ...triScope(1, '.normal.escaped\\,character.ǝpoɔıun.瀡.with-dash.with_underscore.number123.MiXeDcAsE'), + + ...triScope(3, '.normal'), + ...triScope(1, '.dummy.normal'), + + ...triScope(3, '.escaped\\,character'), + ...triScope(1, '.dummy.escaped\\,character'), + + ...triScope(3, '.ǝpoɔıun'), + ...triScope(1, '.dummy.ǝpoɔıun'), + + ...triScope(3, '.瀡'), + ...triScope(1, '.dummy.瀡'), + + ...triScope(3, '.with-dash'), + ...triScope(1, '.dummy.with-dash'), + + ...triScope(3, '.with_underscore'), + ...triScope(1, '.dummy.with_underscore'), + + ...triScope(3, '.number123'), + ...triScope(1, '.dummy.number123'), + + ...triScope(3, '.MiXeDcAsE'), + ...triScope(1, '.dummy.MiXeDcAsE'), + ], + } satisfies Scenario)), + + ...allTemplates.map(([name, markup]) => ({ + name: `selectNthChild/${name}`, + markup, + markupMode: getMarkupMode(name), + setupPage: async (page) => { + await initPage(page, name); + await page.evaluate((n) => { + const win = window as BugWin; + const host = win.__slick.resetHost(); + for (let i = 1; i <= 10; i++) { + win.__slick.add('div', { id: `${i}` }, host); + } + }, name); + }, + cases: [ + { select: ':nth-child(0)', ref: { by: 'id', id: 'host' }, expect: { ids: [] } }, + { select: ':nth-child(1)', ref: { by: 'id', id: 'host' }, expect: { ids: ['1'] } }, + { select: ':nth-child(10)', ref: { by: 'id', id: 'host' }, expect: { ids: ['10'] } }, + { select: ':nth-child(11)', ref: { by: 'id', id: 'host' }, expect: { ids: [] } }, + + { select: ':nth-child(-1)', ref: { by: 'id', id: 'host' }, expect: { ids: [] } }, + + { select: ':nth-child(even)', ref: { by: 'id', id: 'host' }, expect: { ids: ['2', '4', '6', '8', '10'] } }, + { select: ':nth-child(odd)', ref: { by: 'id', id: 'host' }, expect: { ids: ['1', '3', '5', '7', '9'] } }, + + { select: ':nth-child(-n)', ref: { by: 'id', id: 'host' }, expect: { ids: [] } }, + { select: ':nth-child(4n+100)', ref: { by: 'id', id: 'host' }, expect: { ids: [] } }, + + { select: ':nth-child(n)', ref: { by: 'id', id: 'host' }, expect: { ids: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] } }, + { select: ':nth-child(-n+100)', ref: { by: 'id', id: 'host' }, expect: { ids: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] } }, + + { select: ':nth-child(2n+5)', ref: { by: 'id', id: 'host' }, expect: { ids: ['5', '7', '9'] } }, + { select: ':nth-child(n+8)', ref: { by: 'id', id: 'host' }, expect: { ids: ['8', '9', '10'] } }, + + { select: ':nth-child(-2n+5)', ref: { by: 'id', id: 'host' }, expect: { ids: ['1', '3', '5'] } }, + { select: ':nth-child(-4n+2)', ref: { by: 'id', id: 'host' }, expect: { ids: ['2'] } }, + { select: ':nth-child(-n+2)', ref: { by: 'id', id: 'host' }, expect: { ids: ['1', '2'] } }, + + { select: ':nth-child(2n):nth-child(3n+1)', ref: { by: 'id', id: 'host' }, expect: { ids: ['4', '10'] } }, + { select: ':nth-child(n+3):nth-child(-n+5)', ref: { by: 'id', id: 'host' }, expect: { ids: ['3', '4', '5'] } }, + + { select: ':nth-child(odd):nth-last-child(odd)', ref: { by: 'id', id: 'host' }, expect: { ids: [] } }, + ], + } satisfies Scenario)), + + { + name: 'xml', + markupMode: 'xml-document', + markup: ` + + tes + + html + + + tes + + + + + + text + + + + + + + + `, + cases: [ + { select: '*', expect: { count: 17 } }, + + { select: 'HTML', expect: { count: 1 } }, + { select: '#id_idnode', expect: { count: 1 } }, + { select: '[id=id_idnode]', expect: { count: 1 } }, + { select: '.class_classNode', expect: { count: 3 } }, + { select: '[class=class_classNode]', expect: { count: 3 } }, + { select: '[className=class_classNode]', expect: { count: 0 } }, + { select: 'camelCasedTag', expect: { count: 3 } }, + { select: '#node[style=border]', expect: { count: 1 } }, + { select: '[href^="http://"]', expect: { count: 1 } }, + + { select: ':root', expect: { count: 1 } }, + { select: 'html:root', expect: { count: 0 } }, + { select: 'HTML:root', expect: { count: 1 } }, + + // Remove custom selectors (jddalton) + // 'camelCasedTag ! :root' + // ':root !>' + + { select: ':root camelCasedTag', expect: { count: 3 } }, + + { select: '[tabindex]', expect: { count: 3 } }, + { select: 'el[tabindex="0"]', expect: { count: 2 } }, + { select: 'el[tabindex="1"]', expect: { count: 1 } }, + ], + }, + + { + name: 'yui', + markupMode: 'html-document', + markup: ` + + + + YUI Selector Test Suite + + + +
    +

    lorem ipsum

    +

    lorem ipsum

    +

    lorem ipsum

    +

    div lorem

    +

    last child

    +
    + +
    +
    child of demo2
    +
    + +
    + + +
    +
      +
    1. foo
    2. +
    3. foo
    4. +
    5. foo
    6. +
    7. foo
    8. +
    9. foo
    10. +
    11. foo
    12. +
    13. foo
    14. +
    15. foo
    16. +
    17. foo
    18. +
    19. foo
    20. +
    +
    +
    + span +
    first div
    + span +
    second div
    +
    third div
    +
    fourth div
    + span +
    + foo +
    + + + + + + + + +
    + +
    + + +
    + +
    +

    H3 - Title

    +

    lorem ipsum dolor sit link

    +
    + +
    +
    contains "' & ]
    +
    + + +
    +
    Window size
    +
    dd1
    +
    Document size
    +
    dd2
    + +
    +
    custom attribute
    + + + + `, + cases: [ + // testTest + { select: '[type=checkbox]' }, + { match: '[type=checkbox], button', ref: { by: 'id', id: 'checkbox-unchecked' }, expect: { ids: ['checkbox-unchecked'] } }, + { match: 'button, [type=checkbox]', ref: { by: 'id', id: 'checkbox-unchecked' }, expect: { ids: ['checkbox-unchecked'] } }, + { match: 'foo, button', ref: { by: 'id', id: 'checkbox-unchecked' }, expect: { ids: [] } }, + { match: '[lang|=en]', ref: { by: 'id', id: 'test-lang-en-us' }, expect: { ids: ['test-lang-en-us'] } }, + { match: '[lang|=en]', ref: { by: 'id', id: 'test-lang-en' }, expect: { ids: ['test-lang-en'] } }, + { match: '[lang|=en]', ref: { by: 'id', id: 'test-lang-none' }, expect: { ids: [] } }, + { match: 'for [type=checkbox]', ref: { by: 'id', id: 'checkbox-unchecked' }, expect: { ids: [] } }, + { match: 'form [type=checkbox]', ref: { by: 'id', id: 'checkbox-unchecked' }, expect: { ids: ['checkbox-unchecked'] } }, + + { match: '[type=checkbox]:checked', ref: { by: 'id', id: 'checkbox-checked' }, expect: { ids: ['checkbox-checked'] } }, + { match: ':checked', ref: { by: 'id', id: 'radio-checked' }, expect: { ids: ['radio-checked'] } }, + { match: ':checked', ref: { by: 'id', id: 'radio-unchecked' }, expect: { ids: [] } }, + { match: '[type=checkbox]:checked', ref: { by: 'id', id: 'checkbox-unchecked' }, expect: { ids: [] } }, + { match: '[type=checkbox]:not(:checked)', ref: { by: 'id', id: 'checkbox-unchecked' }, expect: { ids: ['checkbox-unchecked'] } }, + + { match: 'dd', ref: { by: 'first', selector: 'dd.test-dd1' }, expect: { count: 1 } }, // dd (dd1) + { match: 'dd', ref: { by: 'first', selector: 'dd.test-dd2' }, expect: { count: 1 } }, // dd (dd2) + + { match: '.test-dd2', ref: { by: 'first', selector: 'dd.test-dd1' }, expect: { count: 0 } }, // .test-dd2 (dd1) + { match: '.test-dd1', ref: { by: 'first', selector: 'dd.test-dd2' }, expect: { count: 0 } }, // .test-dd1 (dd2) + + { match: '.test-dd1', ref: { by: 'first', selector: 'dd.test-dd1' }, expect: { count: 1 } }, // .test-dd1 + { match: '.test-dd2', ref: { by: 'first', selector: 'dd.test-dd2' }, expect: { count: 1 } }, // .test-dd2 + + { match: 'dd', ref: { by: 'first', selector: 'dd.test-dd1' }, expect: { count: 1 } }, // dd (dd1) + { match: 'dd', ref: { by: 'first', selector: 'dd.test-dd2' }, expect: { count: 1 } }, // dd (dd2) + + // testRootQuery + { select: 'li', expect: { count: 10 } }, + { select: '#root-test li', expect: { count: 10 } }, + { select: '#root-tes li', ref: { by: 'id', id: 'demo' }, expect: { count: 0 } }, + + { first: 'a span', ref: { by: 'id', id: 'mod1' }, expect: { count: 1 } }, + { first: 'a', ref: { by: 'id', id: 'mod1' }, expect: { count: 1 } }, + { select: 'a span, a', ref: { by: 'id', id: 'mod1' }, expect: { count: 2 } }, + { select: 'a, a span', ref: { by: 'id', id: 'mod1' }, expect: { count: 2 } }, + + { select: 'body p', ref: { by: 'first', selector: 'body' }, expect: { count: 6 } }, + { select: '#root-test li', ref: { by: 'id', id: 'nth-test' }, expect: { count: 10 } }, + + // testNthLastChild + { select: 'li:nth-last-child(odd)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li.even', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-last-child(2n)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li.odd', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-last-child(even)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li.odd', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-last-child(2n+0)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li.odd', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-last-child(2n+1)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li.even', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-last-child(4n+1)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li.last-four-1', ref: { by: 'id', id: 'nth-test' } } } }, + + // testNthType + { select: 'li:nth-of-type(odd)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li.odd', ref: { by: 'id', id: 'nth-test' } } } }, + { select: '#nth-type-test div:nth-of-type(even)', expect: { equivalentCase: { select: '#nth-type-test div.even' } } }, + { select: '#nth-type-test div:nth-of-type(2n)', expect: { equivalentCase: { select: '#nth-type-test div.even' } } }, + { select: '#nth-type-test div:nth-of-type(3)' }, + + // testNthChild + { select: 'li:nth-child(2)', ref: { by: 'id', id: 'nth-test' } }, + { select: 'li:nth-child(0n+2)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li:nth-child(2)', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-child(3n+1)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li.three-1', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-child(n+1)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-child(2n+1)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li.odd', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-child(odd)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li.odd', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-child(2n+0)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li.even', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-child(2n)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li.even', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-child(even)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li.even', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-child(4n+1)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li.four-1', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-child(4n+2)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li.four-2', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-child(4n+3)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li.four-3', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-child(4n+4)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li.four-4', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-child(0n+1)', ref: { by: 'id', id: 'nth-test' } }, + { select: 'li:nth-child(1)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li:nth-child(0n+1)', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-child(1n+0)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li', ref: { by: 'id', id: 'nth-test' } } } }, + { select: 'li:nth-child(n+0)', ref: { by: 'id', id: 'nth-test' }, expect: { equivalentCase: { select: 'li', ref: { by: 'id', id: 'nth-test' } } } }, + + // testQuery + { select: 'p, p', expect: { equivalentCase: { select: 'p' } } }, + { first: 'p', expect: { count: 1 } }, + { select: '.Foo', expect: { count: 0 } }, + { select: '#root-test', expect: { count: 1, ids: ['root-test'] } }, + { select: '#demo.bar p', expect: { count: 0 } }, + { select: '#demo.foo p', expect: { equivalentCase: { select: '#demo p' } } }, + { select: '.foo p', expect: { equivalentCase: { select: '#demo p' } } }, + { select: '#demo p', expect: { count: 5 } }, + { select: 'p > em', expect: { count: 1, equivalentCase: { first: '#demo-first-child > *' } } }, + { select: '[class~=para]', expect: { count: 3 } }, + { select: '[class~="para"]', expect: { equivalentCase: { select: '[class~=para]' } } }, + { select: 'body div p', expect: { count: 6 } }, + { select: '#demo .madeup', expect: { count: 0 } }, + { select: 'div .para', expect: { count: 3 } }, + { select: '#demo .first', expect: { count: 1, ids: ['demo-first-child'] } }, + { select: 'div', expect: { count: 19 } }, + { select: 'body div', expect: { count: 19 } }, + { select: '.Bar', expect: { count: 1, ids: ['class-bar'] } }, + { select: '#fake-id-not-in-doc', expect: { count: 0 } }, + { first: 'label[for=checkbox-unchecked]', expect: { count: 1, ids: ['label-checkbox-unchecked'] } }, + { select: '.not-button', ref: { by: 'id', id: 'test-inputs' }, expect: { equivalentCase: { select: 'input:not([type=button])', ref: { by: 'id', id: 'test-inputs' } } } }, + { first: '#test-select', expect: { count: 1, ids: ['test-select'] } }, + { first: '[rel^=style]' }, + { first: 'div[rel^=foo2]', expect: { count: 1, ids: ['test-rel-div'] } }, + { first: "div[rel^='foo2']", expect: { equivalentCase: { first: 'div[rel^=foo2]' } } }, + { first: "input[name='foo.bar']", expect: { count: 1, ids: ['foo-bar'] } }, + { select: '#demo > p:not(.last)', expect: { count: 2, includesIds: ['demo-first-child'] } }, + { first: "[id^='foo-']", expect: { count: 1, ids: ['foo-bar'] } }, + { first: '#test-custom-attr[foo=bar]', expect: { count: 1, ids: ['test-custom-attr'] } }, + { first: 'div[foo=bar]', expect: { equivalentCase: { first: '#test-custom-attr[foo=bar]' } } }, + { first: 'div#test-custom-attr[foo=bar]', expect: { equivalentCase: { first: '#test-custom-attr[foo=bar]' } } }, + { first: 'div[foo]', expect: { count: 1, ids: ['test-custom-attr'] } }, + { select: '[foo]', expect: { count: 1, ids: ['test-custom-attr'] } }, + + // testPseudo + { match: ':last-child', ref: { by: 'id', id: 'demo-last-child' }, expect: { count: 1 } }, + { match: 'p:first-child', ref: { by: 'id', id: 'demo-first-child' }, expect: { count: 1, ids: ['demo-first-child'] } }, + { match: ':first-child', ref: { by: 'id', id: 'demo-first-child' }, expect: { count: 1, ids: ['demo-first-child'] } }, + { match: ':first-child.last', ref: { by: 'id', id: 'demo-first-child' }, expect: { count: 0 } }, + { match: ':first-child.first', ref: { by: 'id', id: 'demo-first-child' }, expect: { count: 1, ids: ['demo-first-child'] } }, + { match: ':only-child', ref: { by: 'id', id: 'demo-first-child' }, expect: { count: 0 } }, + { match: ':not(p)', ref: { by: 'id', id: 'demo' }, expect: { count: 1, ids: ['demo'] } }, + { match: ':not(.last)', ref: { by: 'id', id: 'demo-first-child' }, expect: { count: 1, ids: ['demo-first-child'] } }, + { match: ':first-of-type', ref: { by: 'id', id: 'demo-first-child' }, expect: { count: 1, ids: ['demo-first-child'] } }, + { match: ':last-of-type', ref: { by: 'id', id: 'demo-last-child' }, expect: { count: 1, ids: ['demo-last-child'] } }, + { match: ':only-of-type', ref: { by: 'id', id: 'demo-first-child' }, expect: { count: 0 } }, + { match: ':empty', ref: { by: 'id', id: 'demo2' }, expect: { count: 0 } }, + { match: ':empty', ref: { by: 'id', id: 'empty' }, expect: { count: 1, ids: ['empty'] } }, + { match: ':not(.foo)', ref: { by: 'id', id: 'demo' }, expect: { count: 0 } }, + + // testAttr + { match: '[title]', ref: { by: 'id', id: 'demo' }, expect: { count: 1, ids: ['demo'] } }, + { match: '[title]', ref: { by: 'id', id: 'demo-first-child' }, expect: { count: 0 } }, + { match: '[id=demo]', ref: { by: 'id', id: 'demo' }, expect: { count: 1, ids: ['demo'] } }, + { match: '[id|=me]', ref: { by: 'id', id: 'demo' }, expect: { count: 0 } }, + { match: '[id~=demo]', ref: { by: 'id', id: 'demo' }, expect: { count: 1, ids: ['demo'] } }, + { match: '[title~=demo]', ref: { by: 'id', id: 'demo' }, expect: { count: 1, ids: ['demo'] } }, + { match: '[id^=de]', ref: { by: 'id', id: 'demo' }, expect: { count: 1, ids: ['demo'] } }, + { match: '[id$=mo]', ref: { by: 'id', id: 'demo' }, expect: { count: 1, ids: ['demo'] } }, + { match: '[id$=m]', ref: { by: 'id', id: 'demo' }, expect: { count: 0 } }, + { match: '[id*=em]', ref: { by: 'id', id: 'demo' }, expect: { count: 1, ids: ['demo'] } }, + { match: '[id*=ex]', ref: { by: 'id', id: 'demo' }, expect: { count: 0 } }, + { match: '[id=demo][title~=demo]', ref: { by: 'id', id: 'demo' }, expect: { count: 1, ids: ['demo'] } }, + { match: 'div[id=demo][title~=demo]', ref: { by: 'id', id: 'demo' }, expect: { count: 1, ids: ['demo'] } }, + { match: 'div[title="this is a demo"]', ref: { by: 'id', id: 'demo' }, expect: { count: 1, ids: ['demo'] } }, + { match: "div[title='this is a demo']", ref: { by: 'id', id: 'demo' }, expect: { count: 1, ids: ['demo'] } }, + { match: '[href="foo.html"]', ref: { by: 'id', id: 'href-test' }, expect: { count: 1, ids: ['href-test'] } }, + { match: '[id=demo][title=demo]', ref: { by: 'id', id: 'demo' }, expect: { count: 0 } }, + + // testClass + { match: '.foo', ref: { by: 'id', id: 'demo' }, expect: { ids: ['demo'] } }, + { match: 'div.foo', ref: { by: 'id', id: 'demo' }, expect: { ids: ['demo'] } }, + { match: 'span.foo', ref: { by: 'id', id: 'demo' }, expect: { ids: [] } }, + { match: '#demo.foo', ref: { by: 'id', id: 'demo' }, expect: { ids: ['demo'] } }, + { match: '.baz', ref: { by: 'id', id: 'demo' }, expect: { ids: [] } }, + { match: '.first.para', ref: { by: 'id', id: 'demo-first-child' }, expect: { ids: ['demo-first-child'] } }, + { match: 'p.first.para', ref: { by: 'id', id: 'demo-first-child' }, expect: { ids: ['demo-first-child'] } }, + { match: '.foo.bar', ref: { by: 'id', id: 'demo' }, expect: { ids: [] } }, + + // testId + { match: '#demo', ref: { by: 'id', id: 'demo' }, expect: { ids: ['demo'] } }, + { match: 'div#demo', ref: { by: 'id', id: 'demo' }, expect: { ids: ['demo'] } }, + { match: 'div#dmo', ref: { by: 'id', id: 'demo' }, expect: { ids: [] } }, + { match: 'span#demo', ref: { by: 'id', id: 'demo' }, expect: { ids: [] } }, + + // testTag + { match: 'div', ref: { by: 'id', id: 'demo' }, expect: { ids: ['demo'] } }, + { match: 'body div', ref: { by: 'id', id: 'demo' }, expect: { ids: ['demo'] } }, + { match: 'span', ref: { by: 'id', id: 'demo' }, expect: { ids: [] } }, + { match: '*', ref: { by: 'id', id: 'demo' }, expect: { ids: ['demo'] } }, + + // testScoped + { select: '#demo > p' }, + { select: 'foo, > p', ref: { by: 'id', id: 'demo' }, expect: { equivalentCase: { select: '#demo > p' } }, status: 'fixme' }, + + // // Old rooted bare-combinator queries like `+ div` / `~ p` do not map to modern element-scoped selectors + // { select: '+ div', ref: { by: 'id', id: 'demo' }, expect: { ids: ['demo2'] } }, + // { select: '#demo-first-child ~ p', expect: { equivalentCase: { select: '~ p', ref: { by: 'id', id: 'demo-first-child' } } } }, + ], + }, + + { + name: 'pseudos/focus', + markup: ` +
    Should become green onclick
    +
    Shouldn't become green onclick
    + Should become green onclick + + `, + steps: [ + { + setupPage: async (page) => { await page.locator('#div').focus(); }, + cases: [ + { select: 'div, input, a, button', expect: { count: 4 } }, + { select: ':focus', expect: { count: 1, ids: ['div'] } }, + { match: ':focus', ref: { by: 'id', id: 'div' }, expect: { count: 1 } }, + { match: ':focus', ref: { by: 'id', id: 'div2' }, expect: { count: 0 } }, + ], + }, + { + setupPage: async (page) => { await page.locator('#anchor').focus(); }, + cases: [ + { select: ':focus', expect: { count: 1, ids: ['anchor'] } }, + ], + }, + { + setupPage: async (page) => { await page.locator('#button').focus(); }, + cases: [ + { select: ':focus', expect: { count: 1, ids: ['button'] } }, + ], + }, + ], + }, + + // srcdoc is a valid iframe pattern, but it does not reproduce the quirks-mode case needed here. + { + name: 'quirks/iframe-srcdoc-markup', + // status: 'only', + status: 'skip', + markupMode: 'html-document', + markup: ` + + + Parent window + + + + + `, + setupPage: async (page) => { + const mode = await page.locator('#ifr').evaluate((iframe) => { + return (iframe as any).contentDocument?.compatMode; + }); + if (mode !== 'BackCompat') throw new Error(`expected quirks iframe, got ${mode}`); + }, + cases: [ + { select: '[class~=fooBar]', ref: { by: 'iframe', id: 'ifr' }, expect: { count: 2 } }, + ], + }, + + { + name: 'quirks/iframe-route-grounded-parent', + // status: 'only', + markupMode: 'html-document', + markup: ` + + + Parent window + + + + + `, + url: 'https://test.local/host.html', + setupPage: async (page) => { + const rootUrl = 'https://test.local'; + const frameUrl = `${rootUrl}/frame.html`; + + await page.route(`${rootUrl}/**`, async route => { + if (route.request().url() === frameUrl) { + await route.fulfill({ + status: 200, + contentType: 'text/html', + body: ` + + quirks test + +
    +
    +
    +
    + + + `, + }); + return; + } + await route.fulfill({ status: 404, body: 'not found' }); + }); + + const frame = page.frame('ifr'); + if (!frame) throw new Error('iframe frame not found'); + + await page.locator('#ifr').evaluate((iframe, src) => { + (iframe as HTMLIFrameElement).src = src; + }, frameUrl); + + await frame.waitForURL(frameUrl); + + const compatMode = await frame.evaluate(() => document.compatMode); + if (compatMode !== 'BackCompat') { + throw new Error(`expected quirks iframe, got ${compatMode}`); + } + + // throw new Error(` + // mode=${await frame.evaluate(() => document.compatMode)} + // attr=${await frame.locator('[class~=fooBar]').count()} + // class=${await frame.locator('.fooBar').count()} + // html=${await frame.content()} + // `); + }, + cases: [ + { select: '.fooBar', ref: { by: 'iframe', id: 'ifr' }, expect: { count: 2 } }, + { select: '[class~=fooBar]', ref: { by: 'iframe', id: 'ifr' }, expect: { count: 1 } }, + + // Historical expectation was 2 here, but I cannot reproduce that with a real routed quirks iframe. + { select: '[class~=fooBar]', ref: { by: 'iframe', id: 'ifr' }, expect: { count: 2 }, status: 'fail' }, + ], + }, + +]); + +function triFind(count: number, selector: string, status?: TestCase['status']): TestCase[] { + const cases: TestCase[] = [ + { select: selector, expect: { count } }, + { first: selector, expect: { count: count ? 1 : 0 } }, + ]; + + if (count) { + cases.push({ match: selector, ref: { by: 'first', selector }, expect: { count: 1 } }); + } + + if (status) { + for (const c of cases) c.status = status; + } + + return cases; +} + +function triScope(count: number, selector: string, status?: TestCase['status']): TestCase[] { + const cases: TestCase[] = [ + { select: selector, expect: { count } }, + { select: selector, ref: { by: 'id', id: 'host' }, expect: { count } }, + { select: selector, ref: { by: 'id', id: 'host', home: 'detached' }, expect: { count } }, + ]; + if (status) { + for (const c of cases) c.status = status; + } + return cases; +} + +async function initPage(page: Page, template: TemplateKey): Promise { + await page.evaluate((n) => { + const win = window as BugWin; + + function isXmlLike(name: string) { + return name === 'xhtml' || name === 'xml' || name === 'svg'; + } + + function createNode(doc: Document) { + if (n === 'svg') return doc.createElementNS('http://www.w3.org/2000/svg', 'rect'); + if (isXmlLike(n)) return doc.createElementNS('http://www.w3.org/1999/xhtml', 'div'); + return doc.createElement('div'); + } + + function getRoot(): Element { + return document.body ?? document.documentElement; + } + + function getHost(): HTMLElement { + let host = document.getElementById('host') as HTMLElement | null; + if (!host) { + host = createNode(document) as HTMLElement; + host.id = 'host'; + getRoot().appendChild(host); + } + return host; + } + + win.__slick = { + getHost, + resetHost() { + const host = getHost(); + host.replaceChildren(); + return host; + }, + add(tag, attrs = {}, parent) { + const el = document.createElement(tag); + for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v); + (parent ?? getHost()).appendChild(el); + return el; + }, + setHostHTML(html) { + const host = getHost(); + host.innerHTML = html; + return host; + }, + }; + }, template); +} + +function getMarkupMode(template: TemplateKey): Scenario['markupMode'] { + if (template === 'xhtml' || template === 'xml') return 'xml-document'; + return 'html-document'; +} diff --git a/test_new/browser/speed.test.ts b/test_new/browser/speed.test.ts new file mode 100644 index 0000000..e12dff1 --- /dev/null +++ b/test_new/browser/speed.test.ts @@ -0,0 +1,286 @@ +import { readFileSync } from 'node:fs'; +import { runScenarios } from './harness/scenarios'; + +const html = readFileSync('test_new/browser/fixtures/speed/selectors.html', 'utf8'); + +runScenarios('speed', 'normal', [ + { + name: 'default', + markup: html, + markupMode: 'html-document', + cases: [ + { select: '#title' }, + { select: 'h1#title' }, + { select: 'div #title' }, + { select: '#changes + #contents' }, + { select: '.note' }, + { select: 'div.note' }, + { select: 'body .note' }, + { select: '.no-toc + .toc' }, + { select: 'div.example' }, + { select: '.title' }, + { select: '.toc' }, + { select: 'p + .note' }, + { select: 'div.example, p.note' }, + { select: 'body' }, + { select: 'div' }, + { select: 'body div' }, + { select: 'div p' }, + { select: 'div > p' }, + { select: 'div + p' }, + { select: 'div ~ p' }, + { select: 'div[class^=exa][class$=mple]' }, + { select: 'p a' }, + { select: 'div p a' }, + { select: 'div > p > a' }, + { select: 'div.example > p > a' }, + { select: 'div + p + ul' }, + { select: 'div ~ p ~ ul' }, + { select: 'div, ul, a' }, + { select: 'h1, h2, h3, h4, h5, h6' }, + { select: 'a[href][lang][class]' }, + { select: 'div[class]' }, + { select: 'div[class=example]' }, + { select: 'div[class^=exa]' }, + { select: 'div[class$=mple]' }, + { select: 'div[class*=e]' }, + { select: 'div[class~=example]' }, + { select: 'div:not(.example)' }, + { select: 'div:nth-child(even)' }, + { select: 'div:nth-child(2n)' }, + { select: 'div:nth-child(odd)' }, + { select: 'div:nth-child(2n+1)' }, + { select: 'div:nth-child(n)' }, + { select: 'p:only-child' }, + { select: 'p:last-child' }, + { select: 'p:first-child' }, + ], + }, + { + name: 'descendants_only', + markup: html, + markupMode: 'html-document', + cases: [ + { select: 'ul li a span' }, + { select: 'ul li span' }, + { select: 'li a span' }, + { select: 'ul a span' }, + { select: 'ul li a' }, + { select: 'ul li' }, + { select: 'li a' }, + { select: 'ul a' }, + { select: 'dl dt code' }, + { select: 'dl dd a' }, + { select: 'dl dd' }, + { select: 'dl dt' }, + { select: 'table tr td' }, + { select: 'table tr' }, + { select: 'tr td a' }, + { select: 'td a' }, + ], + }, + { + name: 'descendant_and_siblings', + markup: html, + markupMode: 'html-document', + cases: [ + { select: 'div ul li a span' }, + { select: 'div ul li a' }, + { select: 'div ul li' }, + { select: 'div ul' }, + { select: 'ul li a span' }, + { select: 'ul li a' }, + { select: 'ul li' }, + { select: 'li a' }, + { select: 'div > ul > li > a > span' }, + { select: 'div > ul > li > a' }, + { select: 'div > ul > li' }, + { select: 'div > ul' }, + { select: 'ul > li > a > span' }, + { select: 'ul > li > a' }, + { select: 'ul > li' }, + { select: 'li > a' }, + { select: 'h2 + p + ul + p' }, + { select: 'h2 + p + ul' }, + { select: 'p + ul + p' }, + { select: 'li + li' }, + { select: 'h2 + ul' }, + { select: 'h2 + p' }, + { select: 'ul + p' }, + { select: 'p + p' }, + { select: 'h2 ~ p ~ ul ~ p' }, + { select: 'h2 ~ p ~ ul' }, + { select: 'p ~ ul ~ p' }, + { select: 'li ~ li' }, + { select: 'h2 ~ ul' }, + { select: 'h2 ~ p' }, + { select: 'ul ~ p' }, + { select: 'p ~ p' }, + ], + }, + { + name: 'tree-structural_child-indexed', + markup: html, + markupMode: 'html-document', + cases: [ + { select: 'div:last-child' }, + { select: 'div:only-child' }, + { select: 'div:first-child' }, + { select: 'div:nth-child(n)' }, + { select: 'div:nth-child(3)' }, + { select: 'div:nth-child(n+3)' }, + { select: 'div:nth-child(+n-3)' }, + { select: 'div:nth-child(2n)' }, + { select: 'div:nth-child(odd)' }, + { select: 'div:nth-child(2n+1)' }, + { select: 'div:nth-child(even)' }, + { select: 'div:nth-last-child(n)' }, + { select: 'div:nth-last-child(3)' }, + { select: 'div:nth-last-child(n+3)' }, + { select: 'div:nth-last-child(+n-3)' }, + { select: 'div:nth-last-child(2n)' }, + { select: 'div:nth-last-child(odd)' }, + { select: 'div:nth-last-child(2n+1)' }, + { select: 'div:nth-last-child(even)' }, + ], + }, + { + name: 'tree-structural_typed_child-indexed', + markup: html, + markupMode: 'html-document', + cases: [ + { select: 'div:last-of-type' }, + { select: 'div:only-of-type' }, + { select: 'div:first-of-type' }, + { select: 'div:nth-of-type(n)' }, + { select: 'div:nth-of-type(3)' }, + { select: 'div:nth-of-type(n+3)' }, + { select: 'div:nth-of-type(+n-3)' }, + { select: 'div:nth-of-type(2n)' }, + { select: 'div:nth-of-type(odd)' }, + { select: 'div:nth-of-type(2n+1)' }, + { select: 'div:nth-of-type(even)' }, + { select: 'div:nth-last-of-type(n)' }, + { select: 'div:nth-last-of-type(3)' }, + { select: 'div:nth-last-of-type(n+3)' }, + { select: 'div:nth-last-of-type(+n-3)' }, + { select: 'div:nth-last-of-type(2n)' }, + { select: 'div:nth-last-of-type(odd)' }, + { select: 'div:nth-last-of-type(2n+1)' }, + { select: 'div:nth-last-of-type(even)' }, + ], + }, + { + name: 'comma-separated_group_or_selector_list', + markup: html, + markupMode: 'html-document', + cases: [ + { select: 'div, ul, li, a' }, + { select: 'div, ul, li' }, + { select: 'ul, li, a' }, + { select: 'div, li' }, + { select: 'div, a' }, + { select: 'ul, li' }, + { select: 'ul, a' }, + { select: 'li, a' }, + { select: 'div, p, a, em' }, + { select: 'div, p, em' }, + { select: 'div, p, a' }, + { select: 'div, p' }, + { select: 'div, a' }, + { select: 'p, em' }, + { select: 'a, em' }, + { select: 'p, a' }, + ], + }, + + { + name: 'negation_tree-structural_child-indexed', + markup: html, + markupMode: 'html-document', + cases: [ + { select: 'div:not(:last-child)' }, + { select: 'div:not(:only-child)' }, + { select: 'div:not(:first-child)' }, + { select: 'div:not(:nth-child(n))' }, + { select: 'div:not(:nth-child(3))' }, + { select: 'div:not(:nth-child(n+3))' }, + { select: 'div:not(:nth-child(+n-3))' }, + { select: 'div:not(:nth-child(2n))' }, + { select: 'div:not(:nth-child(odd))' }, + { select: 'div:not(:nth-child(2n+1))' }, + { select: 'div:not(:nth-child(even))' }, + { select: 'div:not(:nth-last-child(n))' }, + { select: 'div:not(:nth-last-child(3))' }, + { select: 'div:not(:nth-last-child(n+3))' }, + { select: 'div:not(:nth-last-child(+n-3))' }, + { select: 'div:not(:nth-last-child(2n))' }, + { select: 'div:not(:nth-last-child(odd))' }, + { select: 'div:not(:nth-last-child(2n+1))' }, + { select: 'div:not(:nth-last-child(even))' }, + ], + }, + { + name: 'negation_tree-structural_typed_child-indexed', + markup: html, + markupMode: 'html-document', + cases: [ + { select: 'div:not(:last-of-type)' }, + { select: 'div:not(:only-of-type)' }, + { select: 'div:not(:first-of-type)' }, + { select: 'div:not(:nth-of-type(n))' }, + { select: 'div:not(:nth-of-type(3))' }, + { select: 'div:not(:nth-of-type(n+3))' }, + { select: 'div:not(:nth-of-type(+n-3))' }, + { select: 'div:not(:nth-of-type(2n))' }, + { select: 'div:not(:nth-of-type(odd))' }, + { select: 'div:not(:nth-of-type(2n+1))' }, + { select: 'div:not(:nth-of-type(even))' }, + { select: 'div:not(:nth-last-of-type(n))' }, + { select: 'div:not(:nth-last-of-type(3))' }, + { select: 'div:not(:nth-last-of-type(n+3))' }, + { select: 'div:not(:nth-last-of-type(+n-3))' }, + { select: 'div:not(:nth-last-of-type(2n))' }, + { select: 'div:not(:nth-last-of-type(odd))' }, + { select: 'div:not(:nth-last-of-type(2n+1))' }, + { select: 'div:not(:nth-last-of-type(even))' }, + ], + }, + { + name: 'matches_and_negation_dynamic_and_user_actions', + markup: html, + markupMode: 'html-document', + cases: [ + { select: ':lang(fr)' }, + { select: ':visited' }, + { select: ':target' }, + // { selector: ':active' }, + { select: ':hover' }, + // { selector: ':focus' }, + { select: ':empty' }, + { select: ':link' }, + { select: ':not(:lang(fr))' }, + { select: ':not(:visited)' }, + { select: ':not(:target)' }, + // { selector: ':not(:active)' }, + { select: ':not(:hover)' }, + // { selector: ':not(:focus)' }, + { select: ':not(:empty)' }, + { select: ':not(:link)' }, + ], + }, + { + // active/focus does not seem to be stable. also, not supported in any of the browsers. + name: 'matches_and_negation_dynamic_and_user_actions - active/focus', + status: 'fixme', + markup: html, + markupMode: 'html-document', + cases: [ + { select: ':active' }, + { select: ':focus' }, + { select: ':not(:active)' }, + { select: ':not(:focus)' }, + ], + }, + +]); \ No newline at end of file diff --git a/test_new/browser/w3c-selector.test.ts b/test_new/browser/w3c-selector.test.ts new file mode 100644 index 0000000..162567c --- /dev/null +++ b/test_new/browser/w3c-selector.test.ts @@ -0,0 +1,21 @@ +// import { expect } from '@playwright/test'; +import { runScenarios } from './harness/scenarios'; + +runScenarios('w3c - selector', 'normal', [ + { + name: ':root selector contexts', + markup: `
    `, + cases: [ + { select: ':root', expect: { count: 1 } }, + { select: ':root', ref: { by: 'id', id: 'foo' }, expect: { count: 0 } }, + { select: ':root', ref: { by: 'id', id: 'foo', home: 'detached' }, expect: { count: 0 } }, + { select: ':root', ref: { by: 'id', id: 'foo', home: 'fragment' }, expect: { count: 0 } }, + + { select: ':root span', ref: { by: 'id', id: 'foo' }, expect: { count: 1 } }, + { select: ':root span', ref: { by: 'id', id: 'foo', home: 'detached' }, expect: { count: 0 } }, + { select: ':root span', ref: { by: 'id', id: 'foo', home: 'fragment' }, expect: { count: 0 } }, + + { closest: ':root > *', ref: { by: 'id', id: 'foo', home: 'detached' }, expect: { count: 0 } }, + ], + }, +]); diff --git a/test_new/browser/w3c.test.ts b/test_new/browser/w3c.test.ts new file mode 100644 index 0000000..913cd43 --- /dev/null +++ b/test_new/browser/w3c.test.ts @@ -0,0 +1,3433 @@ +import { expect } from '@playwright/test'; +import { runScenarios } from './harness/scenarios'; + +runScenarios('w3c iframes', 'normal', [ + { + name: 'css/selectors/syntax', + markup: ` + + Selectors: syntax of case-sensitivity attribute selector + + +
    +
    + + + `, + setupPage: async (page) => { + page.on('console', (msg) => { console.log(`[browser:${msg.type()}] ${msg.text()}`); }); + page.on('pageerror', (err) => { console.log(`[pageerror] ${err.message}`); }); + + const results = await page.evaluate(async () => { + + const valid = [ + "[foo='BAR'] /* sanity check (valid) */", + "[foo='bar' i]", + "[foo='bar' I]", + "[foo=bar i]", + '[foo="bar" i]', + "[foo='bar'i]", + "[foo='bar'i ]", + "[foo='bar' i ]", + "[foo='bar' /**/ i]", + "[foo='bar' i /**/ ]", + "[foo='bar'/**/i/**/]", + "[foo=bar/**/i]", + "[foo='bar'\ti\t] /* \\t */", + "[foo='bar'\ni\n] /* \\n */", + "[foo='bar'\ri\r] /* \\r */", + "[foo='bar' \\i]", + "[foo='bar' \\69]", + "[foo~='bar' i]", + "[foo^='bar' i]", + "[foo$='bar' i]", + "[foo*='bar' i]", + "[foo|='bar' i]", + "[|foo='bar' i]", + "[*|foo='bar' i]", + ]; + + const invalid = [ + "[foo[ /* sanity check (invalid) */", + "[foo='bar' i i]", + "[foo i ='bar']", + "[foo= i 'bar']", + "[i foo='bar']", + "[foo='bar' i\u0000] /* \\0 */", + "[foo='bar' \u0130]", + "[foo='bar' \u0131]", + "[foo='bar' ii]", + "[foo='bar' ij]", + "[foo='bar' j]", + "[foo='bar' \\\\i]", + "[foo='bar' \\\\69]", + "[foo='bar' i()]", + "[foo='bar' i ()]", + "[foo='bar' () i]", + "[foo='bar' (i)]", + "[foo='bar' i []]", + "[foo='bar' [] i]", + "[foo='bar' [i]]", + "[foo='bar' i {}]", + "[foo='bar' {} i]", + "[foo='bar' {i}]", + "[foo='bar' 1i]", + "[foo='bar' 1]", + "[foo='bar' 'i']", + "[foo='bar' url(i)]", + "[foo='bar' ,i]", + "[foo='bar' i,]", + "[foo='bar']i", + "[foo='bar' |i]", + "[foo='bar' \\|i]", + "[foo='bar' *|i]", + "[foo='bar' \\*|i]", + "[foo='bar' *]", + "[foo='bar' \\*]", + "[foo i]", + "[foo/**/i]", + ]; + + const quirksFrame = document.querySelector('#quirks')!; + const xmlFrame = document.querySelector('#xml')!; + + const waitForLoad = (frame: HTMLIFrameElement) => + new Promise((resolve) => { + frame.addEventListener('load', () => resolve(), { once: true }); + }); + + const quirksLoaded = waitForLoad(quirksFrame); + const xmlLoaded = waitForLoad(xmlFrame); + + quirksFrame.srcdoc = [ + '', + '
    ', + '', + ].join('\n'); + + xmlFrame.srcdoc = [ + '', + ' ', + ' ', + ' ', + ' ', + '
    ', + ' ', + ' ', + '', + ].join('\n'); + + await quirksLoaded; + await xmlLoaded; + + type Win = Window & typeof globalThis & { mode: string }; + const win = window as Win; + const quirks = quirksFrame.contentWindow as Win; + const xml = xmlFrame.contentWindow as Win; + + win.mode = 'top'; + quirks.mode = 'quirks'; + xml.mode = 'XML'; + + const results: [string, string, boolean][] = []; + const assert_equals = (actual: unknown, expected: unknown, testName: string, failMsg: string) => { + const pass = actual === expected; + results.push([testName, failMsg, pass]); + }; + const assert_throws = (expectedError: string, func: () => void, testName: string, failMsg: string) => { + let threw = false; + try { + func(); + } catch (e) { + threw = true; + assert_equals((e as Error).name, expectedError, testName, failMsg + ' threw wrong error'); + } + assert_equals(threw, true, testName, failMsg + ' did not throw'); + }; + + [win, quirks, xml].forEach(function(global) { + const style = global.document.getElementsByTagName('style')[0]!; + const elm = global.document.getElementById('test')!; + function clean_slate(testName: string) { + style.textContent = ''; + assert_equals(style.sheet?.cssRules.length, 0, testName, 'CSSOM was not empty for empty stylesheet'); + assert_equals(global.getComputedStyle(elm).visibility, 'visible', testName, 'computed style for empty stylesheet'); + } + valid.forEach(function(s) { + { + const testName = s + ' in ' + global.mode; + clean_slate(testName); + style.textContent = s + ' { visibility:hidden }'; + assert_equals(style.sheet?.cssRules.length, 1, testName, 'valid rule didn\'t parse into CSSOM'); + assert_equals(global.getComputedStyle(elm).visibility, 'hidden', testName, 'valid selector didn\'t match'); + }; + { + const testName = s + ' with querySelector in ' + global.mode; + assert_equals(global.document.querySelector(s), elm, testName, 'valid selector'); + }; + }); + invalid.forEach(function(s) { + { + const testName = s + ' in ' + global.mode; + clean_slate(testName); + style.textContent = s + ' { visibility:hidden }'; + assert_equals(style.sheet?.cssRules.length, 0, testName, 'invalid rule parsed into CSSOM'); + assert_equals(global.getComputedStyle(elm).visibility, 'visible', testName, 'invalid selector matched'); + }; + { + const testName = s + ' with querySelector in ' + global.mode; + assert_throws("SyntaxError", function() { + global.document.querySelector(s); + }, testName, 'invalid selector'); + }; + }); + }); + + return results; + }); + + // console.log(results); + for (const [testName, failMsg, pass] of results) { + expect(pass, `${testName}: ${failMsg}`).toBe(true); + } + }, + cases: [], + }, +]); + +runScenarios('w3c', 'normal', [ + { + name: 'css/selectors/syntax', + status: 'fixme', + markup: ` + + Selectors: syntax of case-sensitivity attribute selector + + +
    +
    + + + `, + cases: [ + { select: "[foo='BAR'] /* sanity check (valid) */" }, + { select: "[foo='bar' i]" }, + { select: "[foo='bar' I]" }, + { select: "[foo=bar i]" }, + { select: '[foo="bar" i]' }, + { select: "[foo='bar'i]" }, + { select: "[foo='bar'i ]" }, + { select: "[foo='bar' i ]" }, + { select: "[foo='bar' /**/ i]" }, + { select: "[foo='bar' i /**/ ]" }, + { select: "[foo='bar'/**/i/**/]" }, + { select: "[foo=bar/**/i]" }, + { select: "[foo='bar'\ti\t] /* \\t */" }, + { select: "[foo='bar'\ni\n] /* \\n */" }, + { select: "[foo='bar'\ri\r] /* \\r */" }, + { select: "[foo='bar' \\i]" }, + { select: "[foo='bar' \\69]" }, + { select: "[foo~='bar' i]" }, + { select: "[foo^='bar' i]" }, + { select: "[foo$='bar' i]" }, + { select: "[foo*='bar' i]" }, + { select: "[foo|='bar' i]" }, + { select: "[|foo='bar' i]" }, + { select: "[*|foo='bar' i]" }, + + { select: "[foo[ /* sanity check (invalid) */", expect: { throws: true } }, + { select: "[foo='bar' i i]", expect: { throws: true } }, + { select: "[foo i ='bar']", expect: { throws: true } }, + { select: "[foo= i 'bar']", expect: { throws: true } }, + { select: "[i foo='bar']", expect: { throws: true } }, + { select: "[foo='bar' i\u0000] /* \\0 */", expect: { throws: true } }, + { select: "[foo='bar' \u0130]", expect: { throws: true } }, + { select: "[foo='bar' \u0131]", expect: { throws: true } }, + { select: "[foo='bar' ii]", expect: { throws: true } }, + { select: "[foo='bar' ij]", expect: { throws: true } }, + { select: "[foo='bar' j]", expect: { throws: true } }, + { select: "[foo='bar' \\\\i]", expect: { throws: true } }, + { select: "[foo='bar' \\\\69]", expect: { throws: true } }, + { select: "[foo='bar' i()]", expect: { throws: true } }, + { select: "[foo='bar' i ()]", expect: { throws: true } }, + { select: "[foo='bar' () i]", expect: { throws: true } }, + { select: "[foo='bar' (i)]", expect: { throws: true } }, + { select: "[foo='bar' i []]", expect: { throws: true } }, + { select: "[foo='bar' [] i]", expect: { throws: true } }, + { select: "[foo='bar' [i]]", expect: { throws: true } }, + { select: "[foo='bar' i {}]", expect: { throws: true } }, + { select: "[foo='bar' {} i]", expect: { throws: true } }, + { select: "[foo='bar' {i}]", expect: { throws: true } }, + { select: "[foo='bar' 1i]", expect: { throws: true } }, + { select: "[foo='bar' 1]", expect: { throws: true } }, + { select: "[foo='bar' 'i']", expect: { throws: true } }, + { select: "[foo='bar' url(i)]", expect: { throws: true } }, + { select: "[foo='bar' ,i]", expect: { throws: true } }, + { select: "[foo='bar' i,]", expect: { throws: true } }, + { select: "[foo='bar']i", expect: { throws: true } }, + { select: "[foo='bar' |i]", expect: { throws: true } }, + { select: "[foo='bar' \\|i]", expect: { throws: true } }, + { select: "[foo='bar' *|i]", expect: { throws: true } }, + { select: "[foo='bar' \\*|i]", expect: { throws: true } }, + { select: "[foo='bar' *]", expect: { throws: true } }, + { select: "[foo='bar' \\*]", expect: { throws: true } }, + { select: "[foo i]", expect: { throws: true } }, + { select: "[foo/**/i]", expect: { throws: true } }, + ], + }, + + { + name: 'css/selectors/semantics', + status: 'fixme', + markup: `
    `, + cases: [], + setupPage: async (page) => { + page.on('console', (msg) => { console.log(`[browser:${msg.type()}] ${msg.text()}`); }); + + const results = await page.evaluate(async () => { + type Attr = [ns: string, name: string, value: string]; + type TestCase = [selector: string, ...attrs: Attr[]]; + + const match: TestCase[] = [ + ["[foo='BAR'] /* sanity check (match) */", ["", "foo", "BAR"]], + ["[foo='bar' i]", ["", "foo", "BAR"]], + ["[foo='' i]", ["", "foo", ""]], + ["[foo='a\u0308' i] /* COMBINING in both */", ["", "foo", "A\u0308"]], + ["[foo='A\u0308' i] /* COMBINING in both */", ["", "foo", "a\u0308"]], + ["[*|foo='bar' i]", ["", "foo", "x"], ["a", "foo", "x"], ["b", "foo", "BAR"], ["c", "foo", "x"]], + ["[*|foo='bar' i]", ["", "foo", "BAR"], ["a", "foo", "x"], ["b", "foo", "x"], ["c", "foo", "x"]], + ["[align='left' i]", ["", "align", "LEFT"]], + ["[align='LEFT' i]", ["", "align", "left"]], + ["[class~='a' i]", ["", "class", "X A B"]], + ["[class~='A' i]", ["", "class", "x a b"]], + ["[id^='a' i]", ["", "id", "AB"]], + ["[id$='A' i]", ["", "id", "xa"]], + ["[lang|='a' i]", ["", "lang", "A-B"]], + ["[lang*='A' i]", ["", "lang", "xab"]], + ["[*|lang='a' i]", ["http://www.w3.org/XML/1998/namespace", "lang", "A"]], + ["[*|lang='A' i]", ["http://www.w3.org/XML/1998/namespace", "lang", "a"]], + // ["@namespace x 'http://www.w3.org/XML/1998/namespace'; [x|lang='A' i]", ["http://www.w3.org/XML/1998/namespace", "lang", "a"]], + ["[foo='bar' i][foo='bar' i]", ["", "foo", "BAR"]], + ["[foo='BAR'][foo='bar' i]", ["", "foo", "BAR"]], + ["[foo='bar' i][foo='BAR']", ["", "foo", "BAR"]], + ["[foo='bar' i]", ["", "FOO", "bar"]], + ]; + const nomatch: TestCase[] = [ + ["[missingattr] /* sanity check (no match) */", ["", "foo", "BAR"]], + ["[foo='' i]", ["", "foo", "BAR"]], + ["[foo='\u0000' i] /* \\0 in selector */", ["", "foo", ""]], + ["[foo='' i] /* \\0 in attribute */", ["", "foo", "\u0000"]], + ["[foo='\u00E4' i]", ["", "foo", "\u00C4"]], + ["[foo='\u00C4' i]", ["", "foo", "\u00E4"]], + ["[foo='a\u0308' i] /* COMBINING in selector */", ["", "foo", "\u00C4"]], + ["[foo~='a\u0308' i] /* COMBINING in selector */", ["", "foo", "\u00E4"]], + ["[foo^='A\u0308' i] /* COMBINING in selector */", ["", "foo", "\u00C4"]], + ["[foo$='A\u0308' i] /* COMBINING in selector */", ["", "foo", "\u00E4"]], + ["[foo*='\u00E4' i] /* COMBINING in attribute */", ["", "foo", "a\u0308"]], + ["[foo|='\u00E4' i] /* COMBINING in attribute */", ["", "foo", "A\u0308"]], + ["[foo='\u00C4' i] /* COMBINING in attribute */", ["", "foo", "a\u0308"]], + ["[foo='\u00C4' i] /* COMBINING in attribute */", ["", "foo", "A\u0308"]], + ["[foo='a\u0308' i] /* COMBINING in selector */", ["", "foo", "a"]], + ["[foo='a\u0308' i] /* COMBINING in selector */", ["", "foo", "A"]], + ["[foo='A\u0308' i] /* COMBINING in selector */", ["", "foo", "a"]], + ["[foo='A\u0308' i] /* COMBINING in selector */", ["", "foo", "A"]], + ["[foo='a' i] /* COMBINING in attribute */", ["", "foo", "a\u0308"]], + ["[foo='A' i] /* COMBINING in attribute */", ["", "foo", "a\u0308"]], + ["[foo='a' i] /* COMBINING in attribute */", ["", "foo", "A\u0308"]], + ["[foo='A' i] /* COMBINING in attribute */", ["", "foo", "A\u0308"]], + ["[foo='i' i]", ["", "foo", "\u0130"]], + ["[foo='i' i]", ["", "foo", "\u0131"]], + ["[foo='I' i]", ["", "foo", "\u0130"]], + ["[foo='I' i]", ["", "foo", "\u0131"]], + ["[foo='\u0130' i]", ["", "foo", "i"]], + ["[foo='\u0131' i]", ["", "foo", "i"]], + ["[foo='\u0130' i]", ["", "foo", "I"]], + ["[foo='\u0131' i]", ["", "foo", "I"]], + ["[foo='bar' i]", ["", "foo", "x"], ["a", "foo", "BAR"]], + ["[|foo='bar' i]", ["", "foo", "x"], ["a", "foo", "BAR"]], + // ["[foo='bar' i]", ["", "FOO", "bar"]], + ["[foo='\t' i] /* tab in selector */", ["", "foo", " "]], + ["[foo=' ' i] /* tab in attribute */", ["", "foo", "\t"]], + // ["@namespace x 'a'; [x|foo='' i]", ["A", "foo", ""]], + // ["@namespace x 'A'; [x|foo='' i]", ["a", "foo", ""]], + ["[foo='bar' i][foo='bar']", ["", "foo", "BAR"]], + ["[foo='bar' i]", ["", "baz", "BAR"]], + ]; + + type Result = 'match' | 'nomatch' | 'throws'; + const results: { selector: string, attrsLabel: string, expected: Result, nw: Result, native: Result }[] = []; + + const runTestCase = (testCase: TestCase, expected: Result) => { + const [selector, ...attrs] = testCase; + + const span = document.createElement('span'); + for (const [ns, name, value] of attrs) { + if (ns) { + span.setAttributeNS(ns, name, value); + } else { + span.setAttribute(name, value); + } + } + const div = document.createElement('div'); + div.appendChild(span); + + let native: Result = 'nomatch'; + try { + native = div.querySelector(selector) === span ? 'match' : 'nomatch'; + } catch (e) { + native = 'throws'; + } + + let nw: Result = 'nomatch'; + try { + nw = NW.Dom.select(selector, div)[0] === span ? 'match' : 'nomatch'; + } catch (e) { + nw = 'throws'; + } + + const attrsLabel = attrs.map(([ns, name, value]) => `${ns ? `${ns}:` : ''}${name}="${value}"`).join(' '); + results.push({ selector, attrsLabel, expected, native, nw }); + } + + match.forEach(testCase => runTestCase(testCase, 'match')); + nomatch.forEach(testCase => runTestCase(testCase, 'nomatch')); + + return results; + }); + + // console.log(results); + for (const r of results) { + const label = `${r.selector} on `; + expect(r.nw, `${label}: nw/native mismatch (${r.nw} vs ${r.native})`).toBe(r.native); + expect(r.native, `${label}: native expected ${r.expected}, got ${r.native}`).toBe(r.expected); + // expect(r.nw, `${label}: nw expected ${r.expected}, got ${r.nw}`).toBe(r.expected); + } + }, + }, + + { + name: 'dom/nodes/child-indexed-pseudo-class', + markup: `
    `, + cases: [ + { select: 'div:first-child' }, + { select: 'div:last-child' }, + { select: 'div:only-child' }, + { select: 'div:first-of-type' }, + { select: 'div:last-of-type' }, + { select: 'div:only-of-type' }, + { select: 'div:nth-child(1)' }, + { select: 'div:nth-child(n)' }, + { select: 'div:nth-last-child(1)' }, + { select: 'div:nth-last-child(n)' }, + { select: 'div:nth-of-type(1)' }, + { select: 'div:nth-of-type(n)' }, + { select: 'div:nth-last-of-type(1)' }, + { select: 'div:nth-last-of-type(n)' }, + + { select: 'div:nth-child(2)', expect: { count: 0 } }, + { select: 'div:nth-last-child(2)', expect: { count: 0 } }, + { select: 'div:nth-of-type(2)', expect: { count: 0 } }, + { select: 'div:nth-last-of-type(2)', expect: { count: 0 } }, + ], + }, + + { + name: 'dome/nodes/missing-right-token', + markupMode: 'html-document', + markup: ` + + + + + + +
    + + +
    + + + `, + cases: [ + { select: 'meta[charset="utf-8"', expect: { ids: ['expected'] } }, + { select: 'meta[charset="utf-8', expect: { ids: ['expected'] } }, + { select: 'span:not([class])', ref: { by: 'id', id: 'container' }, expect: { count: 1 } }, + { select: 'span:not([class)', ref: { by: 'id', id: 'container' }, expect: { throws: true } }, + ], + }, + + { + name: 'dom/nodes/element-closest', + markupMode: 'html-document', + markup: ` + + + + Test for Element.closest + + +
    + + + `, + cases: [ + { closest: 'select', ref: { by: 'id', id: 'test12' }, expect: { ids: ['test3'] } }, + { closest: 'fieldset', ref: { by: 'id', id: 'test13' }, expect: { ids: ['test2'] } }, + { closest: 'div', ref: { by: 'id', id: 'test13' }, expect: { ids: ['test6'] } }, + { closest: 'body', ref: { by: 'id', id: 'test3' }, expect: { ids: ['body'] } }, + + { closest: '[default]', ref: { by: 'id', id: 'test4' }, expect: { ids: ['test4'] } }, + { closest: '[selected]', ref: { by: 'id', id: 'test4' }, expect: { count: 0 } }, + { closest: '[selected]', ref: { by: 'id', id: 'test11' }, expect: { ids: ['test11'] } }, + { closest: '[name="form-a"]', ref: { by: 'id', id: 'test12' }, expect: { ids: ['test5'] } }, + { closest: 'form[name="form-a"]', ref: { by: 'id', id: 'test13' }, expect: { ids: ['test5'] } }, + { closest: 'input[required]', ref: { by: 'id', id: 'test9' }, expect: { ids: ['test9'] } }, + { closest: 'select[required]', ref: { by: 'id', id: 'test9' }, expect: { count: 0 } }, + + { closest: 'div:not(.div1)', ref: { by: 'id', id: 'test13' }, expect: { ids: ['test7'] } }, + { closest: 'div.div3', ref: { by: 'id', id: 'test6' }, expect: { ids: ['test8'] } }, + { closest: 'div#test7', ref: { by: 'id', id: 'test1' }, expect: { ids: ['test7'] } }, + + { closest: '.div3 > .div2', ref: { by: 'id', id: 'test12' }, expect: { ids: ['test7'] } }, + { closest: '[class="div2"]:has(div)', ref: { by: 'id', id: 'test12' }, expect: { ids: ['test7'] } }, + { closest: '.div3 > .div1', ref: { by: 'id', id: 'test12' }, expect: { count: 0 } }, + { closest: 'form > input[required]', ref: { by: 'id', id: 'test9' }, expect: { count: 0 } }, + { closest: 'fieldset > select[required]', ref: { by: 'id', id: 'test12' }, expect: { ids: ['test3'] } }, + + { closest: 'input + fieldset', ref: { by: 'id', id: 'test6' }, expect: { count: 0 } }, + { closest: 'form + form', ref: { by: 'id', id: 'test3' }, expect: { ids: ['test5'] } }, + { closest: 'form + form', ref: { by: 'id', id: 'test5' }, expect: { ids: ['test5'] } }, + + { closest: ':empty', ref: { by: 'id', id: 'test10' }, expect: { ids: ['test10'] } }, + { closest: ':last-child', ref: { by: 'id', id: 'test11' }, expect: { ids: ['test2'] } }, + { closest: ':first-child', ref: { by: 'id', id: 'test12' }, expect: { ids: ['test3'] } }, + { closest: ':invalid', ref: { by: 'id', id: 'test11' }, expect: { ids: ['test2'] } }, + + { closest: ':scope', ref: { by: 'id', id: 'test4' }, expect: { ids: ['test4'] } }, + { closest: 'select > :scope', ref: { by: 'id', id: 'test4' }, expect: { ids: ['test4'] } }, + { closest: 'div > :scope', ref: { by: 'id', id: 'test4' }, expect: { count: 0 } }, + { closest: ':has(> :scope)', ref: { by: 'id', id: 'test4' }, expect: { ids: ['test3'] } }, + ], + }, + + { + name: 'dom/nodes/selectors', + markupMode: 'html-document', + markup: ` + + + + + Selectors-API Test Suite: HTML with Selectors Level 2 using TestHarness: Test Document + + + + + + + + +
    +
    + +
    +

    Universal selector tests inside element with id="universal".

    +
    +
    Some preformatted text with some embedded code
    +

    This is a normal link: W3C

    +
    Some more nested elements code hyperlink
    +
    + +
    +
    +
    +
    +
    +

    +
    
    +          
    +
      + + + + +
      + +
      +
      +
      +
      +
      + +
      + + + + + + + + + +
      + +
      +
      + +
      +
      +
      +
      + +
      +
      + + + + + + + + + +

      +
      + +
      +
      +
      +
      +
      +
      + +
      + + + + +
      +
      +
      +
      +
      + +

      +
      + +
      + + + + +
      +
      +
      +
      + +

      +
      + +
      + + + + +
      +
      +
      +
      +
      +
      + +

      +
      + +
      + + + + +
      + +
        +
      1. +
      2. +
      3. +
      4. +
      5. +
      6. +
      7. +
      8. +
      9. +
      10. +
      11. +
      12. +
      + +

      + span1 + em1 + + em2 + span2 + strong1 + em3 + span3 + span4 + strong2 + em4 +

      +
      + +
      +
      +
      +
      + +

      +

      +

      +
      + +
      +

      +

      +

      + +
      +
      +
      +
      + +
      +

      + +

      +

      + + +

      +

      + + + +

      +
      > + +
      +

      +

      +

      +

      Text node

      +

      +
      + + + +
      +
      +
      +
      +
      +
      + +
      + + + + + + + + + + + + + + + + + + + + + + + +
      + +
      +
      +
      +
      + +

      +

      +

      +
      + +
      All pseudo-element tests
      + +
      +

      +

      +

      + + +
      +
      +

      +
      +

      +
      +
      +
      +
      + + + + + + +
      + +
      +
      +
      + +
        +
      • +
      • +
      • +
      • +
      + + + + + + +
      + +
      +
      +
      +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      +
      +
      +

      +
      +
      +
      +

      +

      +
      + +
      +
      +
      +
      +
      +
      +

      +
      +
      +
      +

      +

      +
      + +
      + + +
      +
      + + + + `, + setupPage: async (page) => { + await page.evaluate(() => { + function setupSpecialElements(doc: Document, parent: Element) { + // Setup null and undefined tests + parent.appendChild(doc.createElement("null")); + parent.appendChild(doc.createElement("undefined")); + + // Setup namespace tests + const anyNS = doc.createElement("div"); + const noNS = doc.createElement("div"); + anyNS.id = "any-namespace"; + noNS.id = "no-namespace"; + + let div = [doc.createElement("div"), + doc.createElementNS("http://www.w3.org/1999/xhtml", "div"), + doc.createElementNS("", "div"), + doc.createElementNS("http://www.example.org/ns", "div")]; + + div[0].id = "any-namespace-div1"; + div[1].id = "any-namespace-div2"; + div[2].setAttribute("id", "any-namespace-div3"); // Non-HTML elements can't use .id property + div[3].setAttribute("id", "any-namespace-div4"); + + for (var i = 0; i < div.length; i++) { + anyNS.appendChild(div[i]) + } + + div = [doc.createElement("div"), + doc.createElementNS("http://www.w3.org/1999/xhtml", "div"), + doc.createElementNS("", "div"), + doc.createElementNS("http://www.example.org/ns", "div")]; + + div[0].id = "no-namespace-div1"; + div[1].id = "no-namespace-div2"; + div[2].setAttribute("id", "no-namespace-div3"); // Non-HTML elements can't use .id property + div[3].setAttribute("id", "no-namespace-div4"); + + for (i = 0; i < div.length; i++) { + noNS.appendChild(div[i]) + } + + parent.appendChild(anyNS); + parent.appendChild(noNS); + + const i1 = doc.getElementById("attr-presence-i1")!; + i1.setAttributeNS("http://www.example.org/ns", "title", ""); + } + + setupSpecialElements(document, document.getElementById("root")!); + + location.hash = '#target'; + }); + }, + cases: [ + // ----------------------------------------------------------------------------- + // Invalid selectors + // ----------------------------------------------------------------------------- + + { select: '', expect: { throws: true } }, + { first: '[', expect: { throws: true } }, + { match: ']', ref: { by: 'id', id: 'root' }, expect: { throws: true } }, + { closest: '(', ref: { by: 'id', id: 'root' }, expect: { throws: true } }, + + { select: ')', expect: { throws: true } }, + { first: '{', expect: { throws: true } }, + { match: '}', ref: { by: 'id', id: 'root' }, expect: { throws: true } }, + { closest: '<', ref: { by: 'id', id: 'root' }, expect: { throws: true } }, + + { select: '>', expect: { throws: true } }, + { first: '#', expect: { throws: true } }, + { match: 'div,', ref: { by: 'id', id: 'root' }, expect: { throws: true } }, + { closest: '.', ref: { by: 'id', id: 'root' }, expect: { throws: true } }, + + { select: '.5cm', expect: { throws: true } }, + { select: '//.5cm', expect: { throws: true } }, + { first: '..test', expect: { throws: true } }, + { match: '.foo..quux', ref: { by: 'id', id: 'root' }, expect: { throws: true } }, + { closest: '.bar.', ref: { by: 'id', id: 'root' }, expect: { throws: true } }, + + { select: 'div & address, p', expect: { throws: true }, status: 'fixme' }, + { first: 'div ++ address, p', expect: { throws: true } }, + { match: 'div ~~ address, p', ref: { by: 'id', id: 'root' }, expect: { throws: true } }, + { closest: '[*=test]', ref: { by: 'id', id: 'root' }, expect: { throws: true } }, + + { select: '[*|*=test]', expect: { throws: true } }, + { first: '[class= space unquoted ]', expect: { throws: true } }, + { match: 'div:example', ref: { by: 'id', id: 'root' }, expect: { throws: true } }, + { closest: ':example', ref: { by: 'id', id: 'root' }, expect: { throws: true } }, + + { select: 'div::example', expect: { throws: true } }, + { first: '::example', expect: { throws: true } }, + { match: ':::before', ref: { by: 'id', id: 'root' }, expect: { throws: true } }, + { closest: ':: before', ref: { by: 'id', id: 'root' }, expect: { throws: true } }, + + { select: 'ns|div', expect: { throws: true } }, + { first: ':not(ns|div)', expect: { throws: true } }, + { match: '^|div', ref: { by: 'id', id: 'root' }, expect: { throws: true } }, + { closest: '$|div', ref: { by: 'id', id: 'root' }, expect: { throws: true } }, + + { select: '>*', expect: { throws: true } }, + + // deduping + { select: 'foo & address, p', expect: { throws: true } }, + { select: 'div:subject', expect: { throws: true } }, + { select: ':canvas', expect: { throws: true } }, + { select: ':viewport', expect: { throws: true } }, + { select: ':window', expect: { throws: true } }, + { select: ':menu', expect: { throws: true } }, + { select: ':table', expect: { throws: true } }, + { select: ':select', expect: { throws: true } }, + { select: '::canvas', expect: { throws: true } }, + { select: '::viewport', expect: { throws: true } }, + { select: '::window', expect: { throws: true } }, + { select: '::menu', expect: { throws: true } }, + { select: '::table', expect: { throws: true } }, + { select: '::select', expect: { throws: true } }, + { select: '', expect: { throws: true } }, + { select: '', expect: { throws: true } }, + { select: '', expect: { throws: true } }, + { select: '', expect: { throws: true } }, + + // ----------------------------------------------------------------------------- + // Valid selectors: querySelectorAll / querySelector + // ----------------------------------------------------------------------------- + + // Type Selector + { select: 'html', expect: { ids: ['html'], equivalentCase: { match: 'html', ref: { by: 'id', id: 'html' } } } }, + { select: 'html', ref: { by: 'id', id: 'root' }, expect: { ids: [] } }, + { select: 'body', expect: { ids: ['body'], equivalentCase: { match: 'body', ref: { by: 'id', id: 'body' } } } }, + { select: 'body', ref: { by: 'id', id: 'root' }, expect: { ids: [] } }, + + // Universal Selector + // Testing "*" for entire an entire context node is handled separately. + { select: '#universal>*', expect: { ids: ['universal-p1', 'universal-hr1', 'universal-pre1', 'universal-p2', 'universal-address1'] } }, + { select: '#universal>*>*', expect: { ids: ['universal-code1', 'universal-span1', 'universal-a1', 'universal-code2'] } }, + { select: '#empty>*', expect: { ids: [] } }, + { select: '#universal *', expect: { ids: ['universal-p1', 'universal-code1', 'universal-hr1', 'universal-pre1', 'universal-span1', 'universal-p2', 'universal-a1', 'universal-address1', 'universal-code2', 'universal-a2'] } }, + + // Attribute Selectors + // - presence [att] + { select: '.attr-presence-div1[align]', expect: { ids: ['attr-presence-div1'] } }, + { select: '.attr-presence-div2[align]', expect: { ids: ['attr-presence-div2'] } }, + { select: '#attr-presence [*|TiTlE]', expect: { ids: ['attr-presence-a1', 'attr-presence-span1', 'attr-presence-i1'] } }, + { select: '[data-attr-presence]', expect: { ids: ['attr-presence-pre1', 'attr-presence-blockquote1'] } }, + { select: '.attr-presence-div3[align], .attr-presence-div4[align]', expect: { ids: [] } }, + { select: 'ul[data-中文]', expect: { ids: ['attr-presence-ul1'] } }, + { select: '#attr-presence-select1 option[selected]', expect: { ids: [] } }, + { select: '#attr-presence-select2 option[selected]', expect: { ids: ['attr-presence-select2-option4'] } }, + { select: '#attr-presence-select3 option[selected]', expect: { ids: ['attr-presence-select3-option2', 'attr-presence-select3-option3'] } }, + + // - value [att=val] + { select: '#attr-value [align="center"]', expect: { ids: ['attr-value-div1'] } }, + { select: '#attr-value [align="center"', expect: { ids: ['attr-value-div1'] } }, + { select: '#attr-value [align=""]', expect: { ids: ['attr-value-div2'] } }, + { select: '#attr-value [align="c"]', expect: { ids: [] } }, + { select: '#attr-value [align="centera"]', expect: { ids: [] } }, + { select: '[data-attr-value="\\e9"]', expect: { ids: ['attr-value-div3'] } }, + { select: '[data-attr-value\\_foo="\\e9"]', expect: { ids: ['attr-value-div4'] } }, + { select: "#attr-value input[type='hidden'],#attr-value input[type='radio']", expect: { ids: ['attr-value-input3', 'attr-value-input4', 'attr-value-input6', 'attr-value-input8', 'attr-value-input9'] } }, + { select: "#attr-value input[type=\"hidden\"],#attr-value input[type='radio']", expect: { ids: ['attr-value-input3', 'attr-value-input4', 'attr-value-input6', 'attr-value-input8', 'attr-value-input9'] } }, + { select: '#attr-value input[type=hidden],#attr-value input[type=radio]', expect: { ids: ['attr-value-input3', 'attr-value-input4', 'attr-value-input6', 'attr-value-input8', 'attr-value-input9'] } }, + { select: '[data-attr-value=中文]', expect: { ids: ['attr-value-div5'] } }, + + // - whitespace-separated list [att~=val] + { select: '#attr-whitespace [class~="div1"]', expect: { ids: ['attr-whitespace-div1'] } }, + { select: '#attr-whitespace [class~=""]', expect: { ids: [] } }, + { select: '[data-attr-whitespace~="div"]', expect: { ids: [] } }, + { select: '[data-attr-whitespace~="\\0000e9"]', expect: { ids: ['attr-whitespace-div4'] } }, + { select: '[data-attr-whitespace\\_foo~="\\e9"]', expect: { ids: ['attr-whitespace-div5'] } }, + { select: "#attr-whitespace a[rel~='bookmark'], #attr-whitespace a[rel~='nofollow']", expect: { ids: ['attr-whitespace-a1', 'attr-whitespace-a2', 'attr-whitespace-a3', 'attr-whitespace-a5', 'attr-whitespace-a7'] } }, + { select: "#attr-whitespace a[rel~=\"bookmark\"],#attr-whitespace a[rel~='nofollow']", expect: { ids: ['attr-whitespace-a1', 'attr-whitespace-a2', 'attr-whitespace-a3', 'attr-whitespace-a5', 'attr-whitespace-a7'] } }, + { select: '#attr-whitespace a[rel~=bookmark], #attr-whitespace a[rel~=nofollow]', expect: { ids: ['attr-whitespace-a1', 'attr-whitespace-a2', 'attr-whitespace-a3', 'attr-whitespace-a5', 'attr-whitespace-a7'] } }, + { select: '#attr-whitespace a[rel~="book mark"]', expect: { ids: [] }, status: 'fixme' } , // fixme + { select: '#attr-whitespace [title~=中文]', expect: { ids: ['attr-whitespace-p1'] } }, + + // - hyphen-separated list [att|=val] + { select: '#attr-hyphen-div1[lang|="en"]', expect: { ids: [] } }, + { select: '#attr-hyphen-div2[lang|="fr"]', expect: { ids: ['attr-hyphen-div2'], equivalentCase: { match: '#attr-hyphen-div2[lang|="fr"]', ref: { by: 'id', id: 'attr-hyphen-div2' } } } }, + { select: '#attr-hyphen-div3[lang|="en"]', expect: { ids: ['attr-hyphen-div3'], equivalentCase: { match: '#attr-hyphen-div3[lang|="en"]', ref: { by: 'id', id: 'attr-hyphen-div3' } } } }, + { select: '#attr-hyphen-div4[lang|="es-AR"]', expect: { ids: [] } }, + + // - substring begins-with [att^=val] (Level 3) + { select: '#attr-begins a[href^="http://www"]', expect: { ids: ['attr-begins-a1', 'attr-begins-a3'] } }, + { select: '#attr-begins [lang^="en-"]', expect: { ids: ['attr-begins-div2', 'attr-begins-div4'] } }, + { select: '#attr-begins [class^=""]', expect: { ids: [] } }, + { select: '#attr-begins [class^=apple]', expect: { ids: [] } }, + { select: "#attr-begins [class^=' apple']", expect: { ids: ['attr-begins-p1'], equivalentCase: { match: "#attr-begins [class^=' apple']", ref: { by: 'id', id: 'attr-begins-p1' } } } }, + { select: '#attr-begins [class^=" apple"]', expect: { ids: ['attr-begins-p1'], equivalentCase: { match: '#attr-begins [class^=" apple"]', ref: { by: 'id', id: 'attr-begins-p1' } } } }, + { select: '#attr-begins [class^= apple]', expect: { ids: [] } }, + + // - substring ends-with [att$=val] (Level 3) + { select: '#attr-ends a[href$=".org"]', expect: { ids: ['attr-ends-a1', 'attr-ends-a3'] } }, + { select: '#attr-ends [lang$="-CH"]', expect: { ids: ['attr-ends-div2', 'attr-ends-div4'] } }, + { select: '#attr-ends [class$=""]', expect: { ids: [] } }, + { select: '#attr-ends [class$=apple]', expect: { ids: [] } }, + { select: "#attr-ends [class$='apple ']", expect: { ids: ['attr-ends-p1'], equivalentCase: { match: "#attr-ends [class$='apple ']", ref: { by: 'id', id: 'attr-ends-p1' } } } }, + { select: '#attr-ends [class$="apple "]', expect: { ids: ['attr-ends-p1'], equivalentCase: { match: '#attr-ends [class$="apple "]', ref: { by: 'id', id: 'attr-ends-p1' } } } }, + { select: '#attr-ends [class$=apple ]', expect: { ids: [] } }, + + // - substring contains [att*=val] (Level 3) + { select: '#attr-contains a[href*="http://www"]', expect: { ids: ['attr-contains-a1', 'attr-contains-a3'] } }, + { select: '#attr-contains a[href*=".org"]', expect: { ids: ['attr-contains-a1', 'attr-contains-a2'] } }, + { select: '#attr-contains a[href*=".example."]', expect: { ids: ['attr-contains-a1', 'attr-contains-a3'] } }, + { select: '#attr-contains [lang*="en-"]', expect: { ids: ['attr-contains-div2', 'attr-contains-div6'] } }, + { select: '#attr-contains [lang*="-CH"]', expect: { ids: ['attr-contains-div3', 'attr-contains-div5'] } }, + { select: '#attr-contains [class*=""]', expect: { ids: [] } }, + { select: "#attr-contains [class*=' apple']", expect: { ids: ['attr-contains-p1'], equivalentCase: { match: "#attr-contains [class*=' apple']", ref: { by: 'id', id: 'attr-contains-p1' } } } }, + { select: "#attr-contains [class*='orange ']", expect: { ids: ['attr-contains-p1'], equivalentCase: { match: "#attr-contains [class*='orange ']", ref: { by: 'id', id: 'attr-contains-p1' } } } }, + { select: "#attr-contains [class*='ple banana ora']", expect: { ids: ['attr-contains-p1'], equivalentCase: { match: "#attr-contains [class*='ple banana ora']", ref: { by: 'id', id: 'attr-contains-p1' } } } }, + { select: '#attr-contains [class*=" apple"]', expect: { ids: ['attr-contains-p1'], equivalentCase: { match: '#attr-contains [class*=" apple"]', ref: { by: 'id', id: 'attr-contains-p1' } } } }, + { select: '#attr-contains [class*="orange "]', expect: { ids: ['attr-contains-p1'], equivalentCase: { match: '#attr-contains [class*="orange "]', ref: { by: 'id', id: 'attr-contains-p1' } } } }, + { select: '#attr-contains [class*="ple banana ora"]', expect: { ids: ['attr-contains-p1'], equivalentCase: { match: '#attr-contains [class*="ple banana ora"]', ref: { by: 'id', id: 'attr-contains-p1' } } } }, + { select: '#attr-contains [class*= apple]', expect: { ids: ['attr-contains-p1'], equivalentCase: { match: '#attr-contains [class*= apple]', ref: { by: 'id', id: 'attr-contains-p1' } } } }, + { select: '#attr-contains [class*=orange ]', expect: { ids: ['attr-contains-p1'], equivalentCase: { match: '#attr-contains [class*=orange ]', ref: { by: 'id', id: 'attr-contains-p1' } } } }, + { select: '#attr-contains [class*= banana ]', expect: { ids: ['attr-contains-p1'], equivalentCase: { match: '#attr-contains [class*= banana ]', ref: { by: 'id', id: 'attr-contains-p1' } } } }, + + // Pseudo-classes + // - :root (Level 3) + { select: ':root', expect: { ids: ['html'], equivalentCase: { match: ':root', ref: { by: 'id', id: 'html' } } } }, + { select: ':root', ref: { by: 'id', id: 'root' }, expect: { ids: [] } }, + + // - :nth-child(n) (Level 3) + // XXX write descriptions + { select: '#pseudo-nth-table1 :nth-child(3)', expect: { ids: ['pseudo-nth-td3', 'pseudo-nth-td9', 'pseudo-nth-tr3', 'pseudo-nth-td15'] } }, + { select: '#pseudo-nth li:nth-child(3n)', expect: { ids: ['pseudo-nth-li3', 'pseudo-nth-li6', 'pseudo-nth-li9', 'pseudo-nth-li12'] } }, + { select: '#pseudo-nth li:nth-child(2n+4)', expect: { ids: ['pseudo-nth-li4', 'pseudo-nth-li6', 'pseudo-nth-li8', 'pseudo-nth-li10', 'pseudo-nth-li12'] } }, + { select: '#pseudo-nth-p1 :nth-child(4n-1)', expect: { ids: ['pseudo-nth-em2', 'pseudo-nth-span3'] } }, + + // - :nth-last-child (Level 3) + { select: '#pseudo-nth-table1 :nth-last-child(3)', expect: { ids: ['pseudo-nth-tr1', 'pseudo-nth-td4', 'pseudo-nth-td10', 'pseudo-nth-td16'] } }, + { select: '#pseudo-nth li:nth-last-child(3n)', expect: { ids: ['pseudo-nth-li1', 'pseudo-nth-li4', 'pseudo-nth-li7', 'pseudo-nth-li10'] } }, + { select: '#pseudo-nth li:nth-last-child(2n+4)', expect: { ids: ['pseudo-nth-li1', 'pseudo-nth-li3', 'pseudo-nth-li5', 'pseudo-nth-li7', 'pseudo-nth-li9'] } }, + { select: '#pseudo-nth-p1 :nth-last-child(4n-1)', expect: { ids: ['pseudo-nth-span2', 'pseudo-nth-span4'] } }, + + // - :nth-of-type(n) (Level 3) + { select: '#pseudo-nth-p1 em:nth-of-type(3)', expect: { ids: ['pseudo-nth-em3'], equivalentCase: { match: '#pseudo-nth-p1 em:nth-of-type(3)', ref: { by: 'id', id: 'pseudo-nth-em3' } } } }, + { select: '#pseudo-nth-p1 :nth-of-type(2n)', expect: { ids: ['pseudo-nth-em2', 'pseudo-nth-span2', 'pseudo-nth-span4', 'pseudo-nth-strong2', 'pseudo-nth-em4'] } }, + { select: '#pseudo-nth-p1 span:nth-of-type(2n-1)', expect: { ids: ['pseudo-nth-span1', 'pseudo-nth-span3'] } }, + + // - :nth-last-of-type(n) (Level 3) + { select: '#pseudo-nth-p1 em:nth-last-of-type(3)', expect: { ids: ['pseudo-nth-em2'], equivalentCase: { match: '#pseudo-nth-p1 em:nth-last-of-type(3)', ref: { by: 'id', id: 'pseudo-nth-em2' } } } }, + { select: '#pseudo-nth-p1 :nth-last-of-type(2n)', expect: { ids: ['pseudo-nth-span1', 'pseudo-nth-em1', 'pseudo-nth-strong1', 'pseudo-nth-em3', 'pseudo-nth-span3'] } }, + { select: '#pseudo-nth-p1 span:nth-last-of-type(2n-1)', expect: { ids: ['pseudo-nth-span2', 'pseudo-nth-span4'] } }, + + // - :first-of-type (Level 3) + { select: '#pseudo-nth-p1 em:first-of-type', expect: { ids: ['pseudo-nth-em1'], equivalentCase: { match: '#pseudo-nth-p1 em:first-of-type', ref: { by: 'id', id: 'pseudo-nth-em1' } } } }, + { select: '#pseudo-nth-p1 :first-of-type', expect: { ids: ['pseudo-nth-span1', 'pseudo-nth-em1', 'pseudo-nth-strong1'] } }, + { select: '#pseudo-nth-table1 tr :first-of-type', expect: { ids: ['pseudo-nth-td1', 'pseudo-nth-td7', 'pseudo-nth-td13'] } }, + + // - :last-of-type (Level 3) + { select: '#pseudo-nth-p1 em:last-of-type', expect: { ids: ['pseudo-nth-em4'], equivalentCase: { match: '#pseudo-nth-p1 em:last-of-type', ref: { by: 'id', id: 'pseudo-nth-em4' } } } }, + { select: '#pseudo-nth-p1 :last-of-type', expect: { ids: ['pseudo-nth-span4', 'pseudo-nth-strong2', 'pseudo-nth-em4'] } }, + { select: '#pseudo-nth-table1 tr :last-of-type', expect: { ids: ['pseudo-nth-td6', 'pseudo-nth-td12', 'pseudo-nth-td18'] } }, + + // - :first-child + { select: '#pseudo-first-child div:first-child', expect: { ids: ['pseudo-first-child-div1'], equivalentCase: { match: '#pseudo-first-child div:first-child', ref: { by: 'id', id: 'pseudo-first-child-div1' } } } }, + { select: '.pseudo-first-child-div2:first-child, .pseudo-first-child-div3:first-child', expect: { ids: [] } }, + { select: '#pseudo-first-child span:first-child', expect: { ids: ['pseudo-first-child-span1', 'pseudo-first-child-span3', 'pseudo-first-child-span5'] } }, + + // - :last-child (Level 3) + { select: '#pseudo-last-child div:last-child', expect: { ids: ['pseudo-last-child-div3'], equivalentCase: { match: '#pseudo-last-child div:last-child', ref: { by: 'id', id: 'pseudo-last-child-div3' } } } }, + { select: '.pseudo-last-child-div1:last-child, .pseudo-last-child-div2:first-child', expect: { ids: [] } }, + { select: '#pseudo-last-child span:last-child', expect: { ids: ['pseudo-last-child-span2', 'pseudo-last-child-span4', 'pseudo-last-child-span6'] } }, + + // - :only-child (Level 3) + { select: '#pseudo-only :only-child', expect: { ids: ['pseudo-only-span1'], equivalentCase: { match: '#pseudo-only :only-child', ref: { by: 'id', id: 'pseudo-only-span1' } } } }, + { select: '#pseudo-only em:only-child', expect: { ids: [] } }, + + // - :only-of-type (Level 3) + { select: '#pseudo-only :only-of-type', expect: { ids: ['pseudo-only-span1', 'pseudo-only-em1'] } }, + { select: '#pseudo-only em:only-of-type', expect: { ids: ['pseudo-only-em1'], equivalentCase: { match: '#pseudo-only em:only-of-type', ref: { by: 'id', id: 'pseudo-only-em1' } } } }, + + // - :empty (Level 3) + { select: '#pseudo-empty p:empty', expect: { ids: ['pseudo-empty-p1', 'pseudo-empty-p2'] } }, + { select: '#pseudo-empty :empty', expect: { ids: ['pseudo-empty-p1', 'pseudo-empty-p2', 'pseudo-empty-span1'] } }, + + // - :link and :visited + // Implementations may treat all visited links as unvisited, so these cannot be tested separately. + // The only guarantee is that ":link,:visited" matches the set of all visited and unvisited links and that they are individually mutually exclusive sets. + { select: '#pseudo-link :link, #pseudo-link :visited', expect: { ids: ['pseudo-link-a1', 'pseudo-link-a2', 'pseudo-link-area1'] } }, + { select: '#head :link, #head :visited', expect: { ids: ['pseudo-link-link1', 'pseudo-link-link2'] }, status: 'fail' }, // spec issue: `:link` no longer matches `` + { select: '#head :link, #head :visited', ref: { by: 'id', id: 'root' }, expect: { ids: [] } }, + { select: ':link:visited', ref: { by: 'id', id: 'root' }, expect: { ids: [] } }, + + // - :target (Level 3) + { select: ':target', ref: { by: 'id', id: 'target', home: 'detached' }, expect: { ids: [] } }, + { select: ':target', expect: { ids: ['target'], equivalentCase: { match: ':target', ref: { by: 'id', id: 'target' } } } }, + + // - :lang() + { select: '#pseudo-lang-div1:lang(en)', expect: { ids: ['pseudo-lang-div1'], equivalentCase: { match: '#pseudo-lang-div1:lang(en)', ref: { by: 'id', id: 'pseudo-lang-div1' } } } }, + { select: '#pseudo-lang-div1:lang(en)', ref: { by: 'id', id: 'root', home: 'fragment' }, expect: { ids: [] } }, + { select: '#pseudo-lang-div2:lang(fr)', expect: { ids: ['pseudo-lang-div2'], equivalentCase: { match: '#pseudo-lang-div2:lang(fr)', ref: { by: 'id', id: 'pseudo-lang-div2' } } } }, + { select: '#pseudo-lang-div3:lang(en)', expect: { ids: ['pseudo-lang-div3'], equivalentCase: { match: '#pseudo-lang-div3:lang(en)', ref: { by: 'id', id: 'pseudo-lang-div3' } } } }, + { select: '#pseudo-lang-div4:lang(es-AR)', expect: { ids: [] } }, + + // - :enabled (Level 3) + { select: '#pseudo-ui :enabled', expect: { ids: ['pseudo-ui-input1', 'pseudo-ui-input2', 'pseudo-ui-input3', 'pseudo-ui-input4', 'pseudo-ui-input5', 'pseudo-ui-input6', 'pseudo-ui-input7', 'pseudo-ui-input8', 'pseudo-ui-input9', 'pseudo-ui-textarea1', 'pseudo-ui-button1'] } }, + + // - :disabled (Level 3) + { select: '#pseudo-ui :disabled', expect: { ids: ['pseudo-ui-input10', 'pseudo-ui-input11', 'pseudo-ui-input12', 'pseudo-ui-input13', 'pseudo-ui-input14', 'pseudo-ui-input15', 'pseudo-ui-input16', 'pseudo-ui-input17', 'pseudo-ui-input18', 'pseudo-ui-textarea2', 'pseudo-ui-button2'] } }, + + // - :checked (Level 3) + { select: '#pseudo-ui :checked', expect: { ids: ['pseudo-ui-input4', 'pseudo-ui-input6', 'pseudo-ui-input13', 'pseudo-ui-input15'] } }, + + // - :not(s) (Level 3) + { select: '#not>:not(div)', expect: { ids: ['not-p1', 'not-p2', 'not-p3'] } }, + { select: '#not * :not(:first-child)', expect: { ids: ['not-em1', 'not-em2', 'not-em3'] } }, + { select: ':not(*)', expect: { ids: [] } }, + { select: ':not(*|*)', expect: { ids: [] }, status: 'fixme' }, + + // Pseudo-elements + // - ::first-line + { select: '#pseudo-element:first-line', expect: { ids: [] } }, + { select: '#pseudo-element::first-line', expect: { ids: [] } }, + + // - ::first-letter + { select: '#pseudo-element:first-letter', expect: { ids: [] } }, + { select: '#pseudo-element::first-letter', expect: { ids: [] } }, + + // - ::before + { select: '#pseudo-element:before', expect: { ids: [] } }, + { select: '#pseudo-element::before', expect: { ids: [] } }, + + // - ::after + { select: '#pseudo-element:after', expect: { ids: [] } }, + { select: '#pseudo-element::after', expect: { ids: [] } }, + + // Class Selectors + { select: '.class-p', expect: { ids: ['class-p1', 'class-p2', 'class-p3'] } }, + { select: '#class .apple.orange.banana', expect: { ids: ['class-div1', 'class-div2', 'class-p4', 'class-div3', 'class-p6', 'class-div4'] } }, + { select: 'div.apple.banana.orange', expect: { ids: ['class-div1', 'class-div2', 'class-div3', 'class-div4'] } }, + { select: '.\u53F0\u5317Ta\u0301ibe\u030Ci', expect: { ids: ['class-span1'], equivalentCase: { match: '.\u53F0\u5317Ta\u0301ibe\u030Ci', ref: { by: 'id', id: 'class-span1' } } } }, + { select: '.\u53F0\u5317', expect: { ids: ['class-span1', 'class-span2'] } }, + { select: '.\u53F0\u5317Ta\u0301ibe\u030Ci.\u53F0\u5317', expect: { ids: ['class-span1'], equivalentCase: { match: '.\u53F0\u5317Ta\u0301ibe\u030Ci.\u53F0\u5317', ref: { by: 'id', id: 'class-span1' } } } }, + { select: '.foo\\:bar', expect: { ids: ['class-span3'], equivalentCase: { match: '.foo\\:bar', ref: { by: 'id', id: 'class-span3' } } } }, + { select: '.test\\.foo\\[5\\]bar', expect: { ids: ['class-span4'], equivalentCase: { match: '.test\\.foo\\[5\\]bar', ref: { by: 'id', id: 'class-span4' } } } }, + + // ID Selectors + { select: '#id #id-div1', expect: { ids: ['id-div1'], equivalentCase: { match: '#id #id-div1', ref: { by: 'id', id: 'id-div1' } } } }, + { select: '#id-div1, #id-div1', expect: { ids: ['id-div1'], equivalentCase: { match: '#id-div1, #id-div1', ref: { by: 'id', id: 'id-div1' } } } }, + { select: '#id-div1, #id-div2', expect: { ids: ['id-div1', 'id-div2'] } }, + { select: 'div#id-div1, div#id-div2', expect: { ids: ['id-div1', 'id-div2'] } }, + { select: '#id #none', expect: { ids: [] } }, + { select: '#none #id-div1', expect: { ids: [] } }, + { select: '#id-li-duplicate', expect: { ids: ['id-li-duplicate', 'id-li-duplicate', 'id-li-duplicate', 'id-li-duplicate'] } }, + + { select: '#\u53F0\u5317Ta\u0301ibe\u030Ci', expect: { ids: ['\u53F0\u5317Ta\u0301ibe\u030Ci'], equivalentCase: { match: '#\u53F0\u5317Ta\u0301ibe\u030Ci', ref: { by: 'id', id: '\u53F0\u5317Ta\u0301ibe\u030Ci' } } } }, + { select: '#\u53F0\u5317', expect: { ids: ['\u53F0\u5317'], equivalentCase: { match: '#\u53F0\u5317', ref: { by: 'id', id: '\u53F0\u5317' } } } }, + { select: '#\u53F0\u5317Ta\u0301ibe\u030Ci, #\u53F0\u5317', expect: { ids: ['\u53F0\u5317Ta\u0301ibe\u030Ci', '\u53F0\u5317'] } }, + + // XXX runMatchesTest() in level2-lib.js can't handle this because obtaining the expected nodes requires escaping characters when generating the selector from 'expect' values + { select: '#\\#foo\\:bar', expect: { ids: ['#foo:bar'] } }, + { select: '#test\\.foo\\[5\\]bar', expect: { ids: ['test.foo[5]bar'] } }, + + // Namespaces + // XXX runMatchesTest() in level2-lib.js can't handle these because non-HTML elements don't have a recognised id + { select: '#any-namespace *|div', expect: { ids: ['any-namespace-div1', 'any-namespace-div2', 'any-namespace-div3', 'any-namespace-div4'] }, status: 'fixme' }, + { select: '#no-namespace |div', expect: { ids: ['no-namespace-div3'] }, status: 'fixme' }, + { select: '#no-namespace |*', expect: { ids: ['no-namespace-div3'] }, status: 'fixme' }, + + // Combinators + // - Descendant combinator ' ' + { select: '#descendant div', expect: { ids: ['descendant-div1', 'descendant-div2', 'descendant-div3', 'descendant-div4'] } }, + { select: 'body #descendant-div1', expect: { ids: ['descendant-div1'], equivalentCase: { match: 'body #descendant-div1', ref: { by: 'id', id: 'descendant-div1' } } } }, + { select: 'div #descendant-div1', expect: { ids: ['descendant-div1'], equivalentCase: { match: 'div #descendant-div1', ref: { by: 'id', id: 'descendant-div1' } } } }, + { select: '#descendant #descendant-div2', expect: { ids: ['descendant-div2'], equivalentCase: { match: '#descendant #descendant-div2', ref: { by: 'id', id: 'descendant-div2' } } } }, + { select: '#descendant .descendant-div2', expect: { ids: ['descendant-div2'], equivalentCase: { match: '#descendant .descendant-div2', ref: { by: 'id', id: 'descendant-div2' } } } }, + { select: '.descendant-div1 .descendant-div3', expect: { ids: ['descendant-div3'], equivalentCase: { match: '.descendant-div1 .descendant-div3', ref: { by: 'id', id: 'descendant-div3' } } } }, + { select: '#descendant-div1 #descendant-div4', expect: { ids: [] } }, + { select: '#descendant\t\r\n#descendant-div2', expect: { ids: ['descendant-div2'], equivalentCase: { match: '#descendant\t\r\n#descendant-div2', ref: { by: 'id', id: 'descendant-div2' } } } }, + + /* The future of this combinator is uncertain, see + * https://github.com/w3c/csswg-drafts/issues/641 + * These tests are commented out until a final decision is made on whether to + * keep the feature in the spec. + * + * Removed from Selectors 4; 4/11/2026 + */ + + // - Descendant combinator '>>' + { select: '#descendant>>div', expect: { ids: ['descendant-div1', 'descendant-div2', 'descendant-div3', 'descendant-div4'] }, status: 'fail' }, + { select: 'body>>#descendant-div1', expect: { ids: ['descendant-div1'] }, status: 'fail' }, + { select: 'div>>#descendant-div1', expect: { ids: ['descendant-div1'] }, status: 'fail' }, + { select: '#descendant>>#descendant-div2', expect: { ids: ['descendant-div2'] }, status: 'fail' }, + { select: '#descendant>>.descendant-div2', expect: { ids: ['descendant-div2'] }, status: 'fail' }, + { select: '.descendant-div1>>.descendant-div3', expect: { ids: ['descendant-div3'] }, status: 'fail' }, + { select: '#descendant-div1>>#descendant-div4', expect: { ids: [] }, status: 'fail' }, + + // - Child combinator '>' + { select: '#child>div', expect: { ids: ['child-div1', 'child-div4'] } }, + { select: 'div>#child-div1', expect: { ids: ['child-div1'], equivalentCase: { match: 'div>#child-div1', ref: { by: 'id', id: 'child-div1' } } } }, + { select: '#child>#child-div1', expect: { ids: ['child-div1'], equivalentCase: { match: '#child>#child-div1', ref: { by: 'id', id: 'child-div1' } } } }, + { select: '#child-div1>.child-div2', expect: { ids: ['child-div2'], equivalentCase: { match: '#child-div1>.child-div2', ref: { by: 'id', id: 'child-div2' } } } }, + { select: '.child-div1>.child-div2', expect: { ids: ['child-div2'], equivalentCase: { match: '.child-div1>.child-div2', ref: { by: 'id', id: 'child-div2' } } } }, + { select: '#child>#child-div3', expect: { ids: [] } }, + { select: '#child-div1>.child-div3', expect: { ids: [] } }, + { select: '.child-div1>.child-div3', expect: { ids: [] } }, + { select: '#child-div1\t\r\n>\t\r\n#child-div2', expect: { ids: ['child-div2'], equivalentCase: { match: '#child-div1\t\r\n>\t\r\n#child-div2', ref: { by: 'id', id: 'child-div2' } } } }, + { select: '#child-div1>\t\r\n#child-div2', expect: { ids: ['child-div2'], equivalentCase: { match: '#child-div1>\t\r\n#child-div2', ref: { by: 'id', id: 'child-div2' } } } }, + { select: '#child-div1\t\r\n>#child-div2', expect: { ids: ['child-div2'], equivalentCase: { match: '#child-div1\t\r\n>#child-div2', ref: { by: 'id', id: 'child-div2' } } } }, + { select: '#child-div1>#child-div2', expect: { ids: ['child-div2'], equivalentCase: { match: '#child-div1>#child-div2', ref: { by: 'id', id: 'child-div2' } } } }, + + // - Adjacent sibling combinator '+' + { select: '#adjacent-div2+div', expect: { ids: ['adjacent-div4'] } }, + { select: 'div+#adjacent-div4', expect: { ids: ['adjacent-div4'], equivalentCase: { match: 'div+#adjacent-div4', ref: { by: 'id', id: 'adjacent-div4' } } } }, + { select: '#adjacent-div2+#adjacent-div4', expect: { ids: ['adjacent-div4'], equivalentCase: { match: '#adjacent-div2+#adjacent-div4', ref: { by: 'id', id: 'adjacent-div4' } } } }, + { select: '#adjacent-div2+.adjacent-div4', expect: { ids: ['adjacent-div4'], equivalentCase: { match: '#adjacent-div2+.adjacent-div4', ref: { by: 'id', id: 'adjacent-div4' } } } }, + { select: '.adjacent-div2+.adjacent-div4', expect: { ids: ['adjacent-div4'], equivalentCase: { match: '.adjacent-div2+.adjacent-div4', ref: { by: 'id', id: 'adjacent-div4' } } } }, + { select: '#adjacent div+p', expect: { ids: ['adjacent-p2'] } }, + { select: '#adjacent-div2+#adjacent-p2, #adjacent-div2+#adjacent-div1', expect: { ids: [] } }, + { select: '#adjacent-p2\t\r\n+\t\r\n#adjacent-p3', expect: { ids: ['adjacent-p3'], equivalentCase: { match: '#adjacent-p2\t\r\n+\t\r\n#adjacent-p3', ref: { by: 'id', id: 'adjacent-p3' } } } }, + { select: '#adjacent-p2+\t\r\n#adjacent-p3', expect: { ids: ['adjacent-p3'], equivalentCase: { match: '#adjacent-p2+\t\r\n#adjacent-p3', ref: { by: 'id', id: 'adjacent-p3' } } } }, + { select: '#adjacent-p2\t\r\n+#adjacent-p3', expect: { ids: ['adjacent-p3'], equivalentCase: { match: '#adjacent-p2\t\r\n+#adjacent-p3', ref: { by: 'id', id: 'adjacent-p3' } } } }, + { select: '#adjacent-p2+#adjacent-p3', expect: { ids: ['adjacent-p3'], equivalentCase: { match: '#adjacent-p2+#adjacent-p3', ref: { by: 'id', id: 'adjacent-p3' } } } }, + + // - General sibling combinator ~ (Level 3) + { select: '#sibling-div2~div', expect: { ids: ['sibling-div4', 'sibling-div6'] } }, + { select: 'div~#sibling-div4', expect: { ids: ['sibling-div4'], equivalentCase: { match: 'div~#sibling-div4', ref: { by: 'id', id: 'sibling-div4' } } } }, + { select: '#sibling-div2~#sibling-div4', expect: { ids: ['sibling-div4'], equivalentCase: { match: '#sibling-div2~#sibling-div4', ref: { by: 'id', id: 'sibling-div4' } } } }, + { select: '#sibling-div2~.sibling-div', expect: { ids: ['sibling-div4', 'sibling-div6'] } }, + { select: '#sibling div~p', expect: { ids: ['sibling-p2', 'sibling-p3'] } }, + { select: '#sibling>p~div', expect: { ids: [] } }, + { select: '#sibling-div2~#sibling-div3, #sibling-div2~#sibling-div1', expect: { ids: [] } }, + { select: '#sibling-p2\t\r\n~\t\r\n#sibling-p3', expect: { ids: ['sibling-p3'], equivalentCase: { match: '#sibling-p2\t\r\n~\t\r\n#sibling-p3', ref: { by: 'id', id: 'sibling-p3' } } } }, + { select: '#sibling-p2~\t\r\n#sibling-p3', expect: { ids: ['sibling-p3'], equivalentCase: { match: '#sibling-p2~\t\r\n#sibling-p3', ref: { by: 'id', id: 'sibling-p3' } } } }, + { select: '#sibling-p2\t\r\n~#sibling-p3', expect: { ids: ['sibling-p3'], equivalentCase: { match: '#sibling-p2\t\r\n~#sibling-p3', ref: { by: 'id', id: 'sibling-p3' } } } }, + { select: '#sibling-p2~#sibling-p3', expect: { ids: ['sibling-p3'], equivalentCase: { match: '#sibling-p2~#sibling-p3', ref: { by: 'id', id: 'sibling-p3' } } } }, + + // Group of selectors (comma) + { select: '#group em\t\r \n,\t\r \n#group strong', expect: { ids: ['group-em1', 'group-strong1'] } }, + { select: '#group em,\t\r\n#group strong', expect: { ids: ['group-em1', 'group-strong1'] } }, + { select: '#group em\t\r\n,#group strong', expect: { ids: ['group-em1', 'group-strong1'] } }, + { select: '#group em,#group strong', expect: { ids: ['group-em1', 'group-strong1'] } }, + + // ----------------------------------------------------------------------------- + // Scoped Selectors + // ----------------------------------------------------------------------------- + + /* + * Scoped selectors -- RIP, 2010–2013. + * + * The abandoned Selectors API Level 2 draft included `find()`, `findAll()`, + * and `matches(selector, refNodes)`. + * + * That spec never advanced beyond Working Draft / Working Group Note status + * and was retired in 2013. Modern DOM standardized the narrower one-argument + * selector APIs instead: `querySelector(All)`, `matches(selector)`, and + * `closest(selector)`. + * + * Unable to migrate the rest of the legacy tests. + */ + ], + }, + + { + name: 'html/semantics/scripting-1/template-end-tag-without-start-one-in-body', + markup: ` + +
      The file contains several </template> tag in HTML body without start one
      + + `, + cases: [ + { select: 'template', expect: { ids: [] } }, + { select: 'div', expect: { count: 1 } }, + ] + }, + + { + name: 'html/semantics/scripting-1/html-start-tag-in-body', + markup: ` + + `, + cases: [ + { select: 'template', expect: { ids: ['tmpl'] } }, + { select: 'html', expect: { count: 1 } }, + { select: '.htmlClass', expect: { ids: [] } }, + { select: 'template > *', expect: { count: 0 } }, + ] + }, + + { + name: 'html/semantics/scripting-1/template-contents-body', + markup: ` + + `, + // BODY tokens inside template contents are ignored + cases: [ + { select: 'template', expect: { count: 1 } }, + { select: 'template > *', expect: { count: 0 } }, + ] + }, + + { + name: 'html/semantics/scripting-1/template-contents-div-no-end-tag', + markup: ` + + `, + setupPage: async (page) => { + const result = await page.evaluate(() => { + const template = document.querySelector('template'); + if (!(template instanceof HTMLTemplateElement)) { + return null; + } + + return { + divCount: template.content.querySelectorAll('div').length, + }; + }); + + expect(result).not.toBeNull(); + expect(result!.divCount).toEqual(1); + }, + cases: [ + { select: 'template', expect: { count: 1 } }, + { select: 'template > div', expect: { count: 1 }, status: 'fail' }, // outside template.content + ] + }, + + { + name: 'html/semantics/scripting-1/template-contents-frameset', + // FRAMESET inside template is ignored; template stays empty. + markup: ` + + `, + cases: [ + { select: 'template', expect: { count: 1 } }, + { select: 'template > *', expect: { count: 0 } }, + ] + }, + + { + name: 'html/semantics/scripting-1/template-contents-head', + // HEAD inside template is ignored; template stays empty. + markup: ` + + `, + cases: [ + { select: 'template', expect: { count: 1 } }, + { select: 'template > *', expect: { count: 0 } }, + ] + }, + + { + name: 'html/semantics/scripting-1/template-contents-html', + // HTML inside template is ignored; template stays empty. + markup: ` + + `, + cases: [ + { select: 'template', expect: { count: 1 } }, + { select: 'template > *', expect: { count: 0 } }, + ] + }, + + { + name: 'html/semantics/scripting-1/template-contents-table-no-end-tag', + markup: ` + + `, + setupPage: async (page) => { + const result = await page.evaluate(() => { + const template = document.querySelector('template'); + if (!(template instanceof HTMLTemplateElement)) { + return null; + } + + return { + tableCount: template.content.querySelectorAll('table').length, + trCount: template.content.querySelectorAll('tr').length, + tdCount: template.content.querySelectorAll('td').length, + }; + }); + + expect(result).not.toBeNull(); + expect(result!.tableCount).toEqual(1); + expect(result!.trCount).toEqual(1); + expect(result!.tdCount).toEqual(1); + }, + cases: [ + { select: 'template', expect: { count: 1 } }, + { select: 'table', expect: { count: 1 }, status: 'fail' }, // outside template.content + { select: 'tr', expect: { count: 1 }, status: 'fail' }, // outside template.content + { select: 'td', expect: { count: 1 }, status: 'fail' }, // outside template.content + ] + }, + + { + name: 'html/semantics/selectors/pseudo-classes/checked-001-manual', + markup: ` +

      X

      +

      X X

      +

      +

      + `, + cases: [ + { select: ':checked', expect: { count: 4 } }, + { select: ':checked + span', expect: { count: 2 } }, + { select: ':checked, :checked + span', expect: { count: 6 } }, + ] + }, + + { + name: 'html/semantics/selectors/pseudo-classes/checked-type-change', + markup: ` + + This text should be green. + `, + setupPage: async (page) => { + const result = await page.evaluate(() => { + const input = document.getElementById('checked') as HTMLInputElement; + const beforeSibling = document.querySelectorAll(':checked + span').length; + input.type = 'radio'; + const afterSibling = document.querySelectorAll(':checked + span').length; + + return { + beforeSibling, + afterSibling, + }; + }); + + expect(result.beforeSibling).toEqual(0); + expect(result.afterSibling).toEqual(1); + }, + cases: [] + }, + + { + name: 'html/semantics/selectors/pseudo-classes/checked', + markup: ` + + + + + + +
      +

      + + + + + + + +
      + `, + setupPage: async (page) => { + const result = await page.evaluate(() => { + const nativeIds = () => [...document.querySelectorAll(':checked')].map(el => el.id); + const nwIds = () => NW.Dom.select(':checked', document).map(el => el.id); + + const native_initial = nativeIds(); + const nw_initial = nwIds(); + + (document.getElementById('checkbox1') as HTMLInputElement).removeAttribute('type'); + (document.getElementById('radio1') as HTMLInputElement).removeAttribute('type'); + + const native_afterRemoveType = nativeIds(); + const nw_afterRemoveType = nwIds(); + + (document.getElementById('option2') as HTMLOptionElement).selected = true; + (document.getElementById('checkbox2') as HTMLInputElement).click(); + (document.getElementById('radio2') as HTMLInputElement).click(); + + const native_afterClick = nativeIds(); + const nw_afterClick = nwIds(); + + return { + native_initial, + nw_initial, + native_afterRemoveType, + nw_afterRemoveType, + native_afterClick, + nw_afterClick, + }; + }); + + expect(result.native_initial).toEqual(['option1', 'checkbox1', 'radio1']); + expect(result.nw_initial).toEqual(['option1', 'checkbox1', 'radio1']); + + expect(result.native_afterRemoveType).toEqual(['option1']); + expect(result.nw_afterRemoveType).toEqual(['option1']); + + expect(result.native_afterClick).toEqual(['option2', 'checkbox2', 'radio2']); + expect(result.nw_afterClick).toEqual(['option2', 'checkbox2', 'radio2']); + }, + cases: [ + { select: ':checked', expect: { ids: ['option2', 'checkbox2', 'radio2'] } }, + ] + }, + + { + name: 'html/semantics/selectors/pseudo-classes/default', + markup: ` +
      + + +
      +
      + + +
      + +
      + +
      + +
      + + +
      +
      + + +
      +
      + +
      + + + + + + + + + + +
      + + +
      +
      + + +
      + `, + setupPage: async (page) => { + const result = await page.evaluate(() => { + const nativeIds = () => [...document.querySelectorAll(':default')].map(el => el.id); + const nwIds = () => NW.Dom.select(':default', document).map(el => el.id); + + const native_initial = nativeIds(); + const nw_initial = nwIds(); + + (document.getElementById('button1') as HTMLButtonElement).type = 'submit'; + + return { + native_initial, + nw_initial, + }; + }); + + expect(result.native_initial).toEqual(['button2', 'button4', 'input3', 'input5', 'input7', 'checkbox1', 'radio1', 'option2', 'button6', 'button8']); + expect(result.nw_initial).toEqual(['button2', 'button4', 'input3', 'input5', 'input7', 'checkbox1', 'radio1', 'option2', 'button6', 'button8']); + }, + cases: [ + { select: ':default', expect: { ids: ['button1', 'button4', 'input3', 'input5', 'input7', 'checkbox1', 'radio1', 'option2', 'button6', 'button8'] } }, + ] + }, + + { + name: 'html/semantics/selectors/pseudo-classes/dir', + markup: ` + + + + + Selector: pseudo-classes (:dir(ltr), :dir(rtl)) + + + + + + + + +
      + WERBEH + HEBREW + HEBREW + WERBEH + HEBREW + إيان + WERBEH + WERBEH + HEBREW + ‮WERBEH‬ + WERBEH + HEBREW + HEBREW + إيان + עברית + + + + + `, + markupMode: 'html-document', + setupPage: async (page) => { + const result = await page.evaluate(() => { + const native_ltr = [...document.querySelectorAll(':dir(ltr)')].map(el => el.id); + const nw_ltr = NW.Dom.select(':dir(ltr)', document).map(el => el.id); + + const bdo = document.createElement('bdo'); + bdo.setAttribute('dir', 'ltr'); + + const native_ltr_afterDetached = [...document.querySelectorAll(':dir(ltr)')].map(el => el.id); + const nw_ltr_afterDetached = NW.Dom.select(':dir(ltr)', document).map(el => el.id); + + return { + native_ltr, + nw_ltr, + native_ltr_afterDetached, + nw_ltr_afterDetached, + }; + }); + + expect(result.native_ltr).toEqual(result.native_ltr_afterDetached); + expect(result.nw_ltr).toEqual(result.nw_ltr_afterDetached); + }, + cases: [ + { select: ':dir(rtl)', expect: { ids: ['bdo1', 'bdi2', 'bdi4', 'span2', 'span5', 'bdo4'] } }, + { select: ':dir(ltr)', expect: { ids: [ + "html", "head", "meta", "title", "link1", "link2", "script1", "script2", "script3", "style", "body", + "log", "bdo2", "bdi1", "bdi3", "span1", "span3", "span4", "span6", "bdo3", "bdo5", "script4" + ] } }, + ] + }, + + { + name: 'html/semantics/selectors/pseudo-classes/dir01', + markup: ` +
      This text is left to right
      this is right to left
      +
      This text is left to rightthis is left to right
      + `, + cases: [ + { select: ':dir(ltr)', expect: { equivalentCase: { select: '*' } } }, + ] + }, + + { + name: 'html/semantics/selectors/pseudo-classes/disabled', + markup: ` + +
      + + + + + + + + + + +
      +
      + +

      +

      +
      + + + + + + + `, + setupPage: async (page) => { + const result = await page.evaluate(() => { + const nativeIds = (sel: string) => [...document.querySelectorAll(sel)].map(el => el.id); + const nwIds = (sel: string) => NW.Dom.select(sel, document).map(el => el.id); + + const native_initial = nativeIds(':disabled'); + const nw_initial = nwIds(':disabled'); + + document.getElementById('button2')!.removeAttribute('disabled'); + const native_afterRemove = nativeIds(':disabled'); + const nw_afterRemove = nwIds(':disabled'); + + document.getElementById('button1')!.setAttribute('disabled', 'disabled'); + const native_afterSet = nativeIds(':disabled'); + const nw_afterSet = nwIds(':disabled'); + + document.getElementById('button1')!.setAttribute('disabled', 'disabled'); + const native_afterSetTwice = nativeIds(':disabled'); + const nw_afterSetTwice = nwIds(':disabled'); + + (document.getElementById('input2') as HTMLInputElement).setAttribute('type', 'submit'); + const native_afterTypeChange = nativeIds(':disabled'); + const nw_afterTypeChange = nwIds(':disabled'); + + const input = document.createElement('input'); + input.setAttribute('disabled', 'disabled'); + const native_afterDetached = nativeIds(':disabled'); + const nw_afterDetached = nwIds(':disabled'); + + const fieldset = document.createElement('fieldset'); + fieldset.id = 'fieldset_nested'; + fieldset.innerHTML = ` + + + + + + +
      + +
      + `; + document.getElementById('fieldset2')!.appendChild(fieldset); + + return { + native_initial, + nw_initial, + native_afterRemove, + nw_afterRemove, + native_afterSet, + nw_afterSet, + native_afterSetTwice, + nw_afterSetTwice, + native_afterTypeChange, + nw_afterTypeChange, + native_afterDetached, + nw_afterDetached, + }; + }); + + expect(result.native_initial).toEqual(['button2', 'input2', 'select2', 'optgroup2', 'option2', 'textarea2', 'fieldset2', 'clubname', 'clubnum']); + expect(result.nw_initial).toEqual(['button2', 'input2', 'select2', 'optgroup2', 'option2', 'textarea2', 'fieldset2', 'clubname', 'clubnum']); + + expect(result.native_afterRemove).toEqual(['input2', 'select2', 'optgroup2', 'option2', 'textarea2', 'fieldset2', 'clubname', 'clubnum']); + expect(result.nw_afterRemove).toEqual(['input2', 'select2', 'optgroup2', 'option2', 'textarea2', 'fieldset2', 'clubname', 'clubnum']); + + expect(result.native_afterSet).toEqual(['button1', 'input2', 'select2', 'optgroup2', 'option2', 'textarea2', 'fieldset2', 'clubname', 'clubnum']); + expect(result.nw_afterSet).toEqual(['button1', 'input2', 'select2', 'optgroup2', 'option2', 'textarea2', 'fieldset2', 'clubname', 'clubnum']); + + expect(result.native_afterSetTwice).toEqual(['button1', 'input2', 'select2', 'optgroup2', 'option2', 'textarea2', 'fieldset2', 'clubname', 'clubnum']); + expect(result.nw_afterSetTwice).toEqual(['button1', 'input2', 'select2', 'optgroup2', 'option2', 'textarea2', 'fieldset2', 'clubname', 'clubnum']); + + expect(result.native_afterTypeChange).toEqual(['button1', 'input2', 'select2', 'optgroup2', 'option2', 'textarea2', 'fieldset2', 'clubname', 'clubnum']); + expect(result.nw_afterTypeChange).toEqual(['button1', 'input2', 'select2', 'optgroup2', 'option2', 'textarea2', 'fieldset2', 'clubname', 'clubnum']); + + expect(result.native_afterDetached).toEqual(['button1', 'input2', 'select2', 'optgroup2', 'option2', 'textarea2', 'fieldset2', 'clubname', 'clubnum']); + expect(result.nw_afterDetached).toEqual(['button1', 'input2', 'select2', 'optgroup2', 'option2', 'textarea2', 'fieldset2', 'clubname', 'clubnum']); + }, + cases: [ + // { select: '#fieldset2 :disabled', expect: { ids: ['clubname', 'clubnum', 'fieldset_nested', 'input_nested', 'button_nested', 'select_nested', 'textarea_nested', 'fieldset_nested2', 'input_nested2'] } }, + ] + }, + + { + name: 'html/semantics/selectors/pseudo-classes/enabled', + markup: ` + + + + + + + + + + + + + + +
      +

      + + + + + +
      +
      +
      + `, + cases: [ + { select: ':enabled', expect: { ids: ['button1', 'input1', 'select1', 'optgroup1', 'option1', 'textarea1', 'submitbutton', 'fieldset1'] } }, + ] + }, + + { + name: 'html/semantics/selectors/pseudo-classes/autofocus', + markup: ` + + `, + setupPage: async (page) => { + await new Promise((resolve) => setTimeout(resolve, 100)); + }, + cases: [ + { select: ':focus', expect: { ids: ['input1'] } }, + ] + }, + + { + name: 'html/semantics/selectors/pseudo-classes/focus-none', + markup: ` + + `, + cases: [ + { select: ':focus', expect: { ids: [] }, status: 'fixme'}, + ] + }, + + { + name: 'html/semantics/selectors/pseudo-classes/focus', + // browsers: ['chromium', 'webkit'], // Firefox doesn't support :focus inside iframe ?? + markup: ` + + Selector: pseudo-classes (:focus) + + + + + + + + + +
      hello
      +
      content
      + + + `, + markupMode: 'html-document', + setupPage: async (page) => { + const result = await page.evaluate(async () => { + const iframe = document.getElementById('iframe') as HTMLIFrameElement; + const inputiframe = iframe.contentDocument?.getElementById('inputiframe'); + if (!inputiframe) throw new Error('Failed to find input inside iframe'); + + const nativeIds = () => [...document.querySelectorAll(':focus')].map(el => el.id); + const nwIds = () => NW.Dom.select(':focus', document).map(el => el.id); + + (document.getElementById('input1'))?.focus(); + const native_input1 = nativeIds(); + const nw_input1 = nwIds(); + + (document.getElementById('div1'))?.focus(); + const native_div1 = nativeIds(); + const nw_div1 = nwIds(); + + (document.getElementById('div2'))?.focus(); + const native_div2 = nativeIds(); + const nw_div2 = nwIds(); + + (document.getElementById('body'))?.focus(); + const native_body = nativeIds(); + const nw_body = nwIds(); + + inputiframe.focus(); + const native_iframe = nativeIds(); + const nw_iframe = nwIds(); + + return { + native_input1, nw_input1, + native_div1, nw_div1, + native_div2, nw_div2, + native_body, nw_body, + native_iframe, nw_iframe, + }; + }); + + expect(result.native_input1).toEqual(['input1']); + expect(result.nw_input1).toEqual(['input1']); + + expect(result.native_div1).toEqual(['div1']); + expect(result.nw_div1).toEqual(['div1']); + + expect(result.native_div2).toEqual(['div2']); + expect(result.nw_div2).toEqual(['div2']); + + expect(result.native_body).toEqual(['body']); + expect(result.nw_body).toEqual(['body']); + + // expect(result.native_iframe).toEqual(['inputiframe']); + // expect(result.nw_iframe).toEqual(['inputiframe']); + }, + cases: [ + { select: 'input', ref: { by: 'iframe', id: 'iframe' }, expect: { ids: ['inputiframe'] } }, + { select: 'input:focus', ref: { by: 'iframe', id: 'iframe' }, expect: { ids: ['inputiframe'] }, status: 'fail' }, + ] + }, + + { + name: 'html/semantics/selectors/pseudo-classes/indeterminate-radio', + markup: ` + +
      + + `, + setupPage: async (page) => { + await page.evaluate(() => { + (document.getElementById('radio1') as HTMLInputElement).indeterminate = true; + }); + }, + cases: [ + { select: 'input:indeterminate + #test', expect: { count: 0 } }, + ] + }, + + { + name: 'html/semantics/selectors/pseudo-classes/indeterminate-type-change', + markup: ` + + This text should be green. + `, + setupPage: async (page) => { + const result = await page.evaluate(() => { + const native_before = [...document.querySelectorAll(':indeterminate + span')].map(el => el.id); + const nw_before = NW.Dom.select(':indeterminate + span', document).map(el => el.id); + + (document.getElementById('indeterminate') as HTMLInputElement).type = 'radio'; + + return { + native_before, + nw_before, + }; + }); + + expect(result.native_before).toEqual([]); + expect(result.nw_before).toEqual([]); + }, + cases: [ + { select: ':indeterminate + span', expect: { ids: ['sibling'] }, status: 'fixme'}, + ] + }, + + { + name: 'html/semantics/selectors/pseudo-classes/indeterminate', + markup: ` + + + + + + + + + + `, + setupPage: async (page) => { + const result = await page.evaluate(() => { + const nativeIds = () => [...document.querySelectorAll(':indeterminate')].map(el => el.id); + const nwIds = () => NW.Dom.select(':indeterminate', document).map(el => el.id); + + const native_initial = nativeIds(); + const nw_initial = nwIds(); + + document.getElementById('radio2')?.setAttribute('checked', 'checked'); + const native_afterCheckedAttr = nativeIds(); + const nw_afterCheckedAttr = nwIds(); + + (document.getElementById('radio4') as HTMLInputElement)?.click(); + const native_afterRadio4Click = nativeIds(); + const nw_afterRadio4Click = nwIds(); + + document.getElementById('progress1')?.setAttribute('value', '20'); + const native_afterProgress1Value = nativeIds(); + const nw_afterProgress1Value = nwIds(); + + document.getElementById('progress2')?.removeAttribute('value'); + const native_afterProgress2Remove = nativeIds(); + const nw_afterProgress2Remove = nwIds(); + + (document.getElementById('checkbox1') as HTMLInputElement).indeterminate = true; + + return { + native_initial, + nw_initial, + native_afterCheckedAttr, + nw_afterCheckedAttr, + native_afterRadio4Click, + nw_afterRadio4Click, + native_afterProgress1Value, + nw_afterProgress1Value, + native_afterProgress2Remove, + nw_afterProgress2Remove, + }; + }); + + expect(result.native_initial).toEqual(['radio2', 'radio3', 'radio4', 'radio5', 'progress1']); + expect(result.nw_initial).toEqual(['radio2', 'radio3', 'radio4', 'radio5', 'progress1']); + + expect(result.native_afterCheckedAttr).toEqual(['radio4', 'radio5', 'progress1']); + expect(result.nw_afterCheckedAttr).toEqual(['radio4', 'radio5', 'progress1']); + + expect(result.native_afterRadio4Click).toEqual(['progress1']); + expect(result.nw_afterRadio4Click).toEqual(['progress1']); + + expect(result.native_afterProgress1Value).toEqual([]); + expect(result.nw_afterProgress1Value).toEqual([]); + + expect(result.native_afterProgress2Remove).toEqual(['progress2']); + expect(result.nw_afterProgress2Remove).toEqual(['progress2']); + }, + cases: [ + { select: ':indeterminate', expect: { ids: ['checkbox1', 'progress2'] } }, + ] + }, + + { + name: 'html/semantics/selectors/pseudo-classes/inrange-outofrange-type-change', + markup: ` + + This text should be green. + + This text should be green. + `, + setupPage: async (page) => { + const result = await page.evaluate(() => { + const native_inRange_before = [...document.querySelectorAll('#t1:in-range + span')].map(el => el.id); + const nw_inRange_before = NW.Dom.select('#t1:in-range + span', document).map(el => el.id); + + const native_outOfRange_before = [...document.querySelectorAll('#t2:out-of-range + span')].map(el => el.id); + const nw_outOfRange_before = NW.Dom.select('#t2:out-of-range + span', document).map(el => el.id); + + (document.getElementById('t1') as HTMLInputElement).type = 'number'; + (document.getElementById('t2') as HTMLInputElement).type = 'number'; + + return { + native_inRange_before, + nw_inRange_before, + native_outOfRange_before, + nw_outOfRange_before, + }; + }); + + expect(result.native_inRange_before).toEqual([]); + expect(result.nw_inRange_before).toEqual([]); + + expect(result.native_outOfRange_before).toEqual([]); + expect(result.nw_outOfRange_before).toEqual([]); + }, + cases: [ + { select: '#t1:in-range + span', expect: { ids: ['sibling1'] } }, + { select: '#t2:out-of-range + span', expect: { ids: ['sibling2'] } }, + ] + }, + + { + name: 'html/semantics/selectors/pseudo-classes/inrange-outofrange', + browsers: ['chromium'], // Firefox and WebKit are flaky here. + markup: ` + + + Selector: pseudo-classes (:in-range, :out-of-range) + + + + + + + +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + `, + steps: [ + { + cases: [ + { select: ':in-range', expect: { ids: ['number1', 'datein', 'timein', 'weekin', 'monthin', 'datetimelocalin', 'range0', 'range1', 'range2', 'range3'] } }, + { select: ':out-of-range', expect: { ids: ['number3', 'number4', 'dateunder', 'dateover', 'timeunder', 'timeover', 'weekunder', 'weekover', 'monthunder', 'monthover', 'datetimelocalunder', 'datetimelocalover'] } }, + ], + }, + { + setupPage: async (page) => { await page.evaluate(() => { (document.getElementById('number1') as HTMLInputElement).value = '-10'; }); }, + cases: [ + { select: ':in-range', expect: { ids: ['datein', 'timein', 'weekin', 'monthin', 'datetimelocalin', 'range0', 'range1', 'range2', 'range3'] } }, + { select: ':out-of-range', expect: { ids: ['number1', 'number3', 'number4', 'dateunder', 'dateover', 'timeunder', 'timeover', 'weekunder', 'weekover', 'monthunder', 'monthover', 'datetimelocalunder', 'datetimelocalover'] } }, + ], + }, + { + setupPage: async (page) => { await page.evaluate(() => { (document.getElementById('number3') as HTMLInputElement).min = '0'; }); }, + cases: [ + { select: ':in-range', expect: { ids: ['number3', 'datein', 'timein', 'weekin', 'monthin', 'datetimelocalin', 'range0', 'range1', 'range2', 'range3'] } }, + { select: ':out-of-range', expect: { ids: ['number1', 'number4', 'dateunder', 'dateover', 'timeunder', 'timeover', 'weekunder', 'weekover', 'monthunder', 'monthover', 'datetimelocalunder', 'datetimelocalover'] } }, + ], + }, + ], + }, + + { + name: 'html/semantics/selectors/pseudo-classes/link', + status: 'fixme', // the original test is sus. link3 doesn't even exist in the DOM... + markup: ` + + + Selector: pseudo-classes (:link) + + +
      + + + + + + + + `, + markupMode: 'html-document', + steps: [ + { + cases: [ + { select: ':link', expect: { ids: ['link1', 'link2', 'link3', 'link7', 'link8', 'link9', 'link10'] } }, + ], + }, + { + setupPage: async (page) => { await page.evaluate(() => { document.getElementById('link9')?.removeAttribute('href'); }); }, + cases: [ + { select: ':link', expect: { ids: ['link1', 'link2', 'link3', 'link7', 'link8', 'link10'] } }, + ], + }, + ], + }, + + { + name: 'html/semantics/selectors/pseudo-classes/placeholder-shown-type-change', + markup: ` + + This text should be green. + `, + steps: [ + { + cases: [ + { select: ':placeholder-shown + span', expect: { ids: [] } }, + ], + }, + { + setupPage: async (page) => { await page.evaluate(() => { (document.getElementById('input') as HTMLInputElement).type = 'text'; }); }, + cases: [ + { select: ':placeholder-shown + span', expect: { ids: ['sibling'] } }, + ], + }, + ], + }, + + { + // source filename is misleading, this test is about both :read-only and :read-write + name: 'html/semantics/selectors/pseudo-classes/readwrite-readonly-type-change', + markup: ` + + This text should be green on lime background. + `, + steps: [ + { + cases: [ + { select: ':required + span', expect: { ids: [] }, status: 'fixme' }, + { select: ':not(:optional) + span', expect: { ids: [] }, status: 'fixme' }, + ], + }, + { + setupPage: async (page) => { await page.evaluate(() => { (document.getElementById('hiddenInput') as HTMLInputElement).type = 'text'; }); }, + cases: [ + { select: ':required + span', expect: { ids: ['sibling'] } }, + { select: ':not(:optional) + span', expect: { ids: ['sibling'] } }, + ], + }, + ], + }, + + { + name: 'html/semantics/selectors/pseudo-classes/readwrite-readonly', + // browsers: ['webkit'], + markup: ` +
      + + + + + + + + + + + +
      + +
      + + + + + +
      + +
      + + +
      + +
      + + +
      + +
      +

      paragraph1.

      +

      paragraph2.

      +
      + `, + markupMode: 'html-document', + steps: [ + { + cases: [ + // WebKit differs here on input[type=color]; expected browser variance. + { select: '#set0 :read-write', expect: { ids: [] }, status: 'fail' }, + { select: '#set0 :read-only', expect: { ids: ['checkbox1', 'hidden1', 'range1', 'color1', 'radio1', 'file1', 'submit1', 'image1', 'button1', 'reset1'] }, status: 'fail' }, + { select: '#set1 :read-write', expect: { ids: ['input1'] } }, + { select: '#set1 :read-only', expect: { ids: ['input2', 'input3', 'input4', 'input5'] } }, + ], + }, + { + setupPage: async (page) => { await page.evaluate(() => { document.getElementById('input1')?.setAttribute('readonly', 'readonly'); }); }, + cases: [ + { select: '#set1 :read-write', expect: { ids: [] } }, + { select: '#set1 :read-only', expect: { ids: ['input1', 'input2', 'input3', 'input4', 'input5'] } }, + ], + }, + { + setupPage: async (page) => { await page.evaluate(() => { document.getElementById('input1')?.removeAttribute('readonly'); }); }, + cases: [ + { select: '#set1 :read-write', expect: { ids: ['input1'] } }, + { select: '#set1 :read-only', expect: { ids: ['input2', 'input3', 'input4', 'input5'] } }, + ], + }, + { + cases: [ + { select: '#set2 :read-write', expect: { ids: ['textarea1'] } }, + { select: '#set2 :read-only', expect: { ids: ['textarea2'] } }, + ], + }, + { + setupPage: async (page) => { await page.evaluate(() => { document.getElementById('textarea1')?.setAttribute('readonly', 'readonly'); }); }, + cases: [ + { select: '#set2 :read-write', expect: { ids: [] } }, + { select: '#set2 :read-only', expect: { ids: ['textarea1', 'textarea2'] } }, + ], + }, + { + cases: [ + { select: '#set3 :read-write', expect: { ids: ['textarea3'] } }, + { select: '#set3 :read-only', expect: { ids: ['textarea4'] } }, + { select: '#set4 :read-write', expect: { ids: ['p2'] } }, + { select: '#set4 :read-only', expect: { ids: ['p1'] } }, + ], + }, + { + setupPage: async (page) => { await page.evaluate(() => { document.designMode = 'on'; }); }, + cases: [ + { select: '#set4 :read-write', expect: { ids: ['p1', 'p2'] }, status: 'fixme' }, + { select: '#set4 :read-only', expect: { ids: [] }, status: 'fixme' }, + ], + }, + ], + }, + + { + name: 'html/semantics/selectors/pseudo-classes/required-optional-hidden', + markup: ` + + This text should be green on lime background. + `, + steps: [ + { + cases: [ + { select: ':required + span', expect: { ids: [] }, status: 'fixme' }, + { select: ':not(:optional) + span', expect: { ids: [] }, status: 'fixme' }, + ], + }, + { + setupPage: async (page) => { await page.evaluate(() => { (document.getElementById('hiddenInput') as HTMLInputElement).type = 'text'; }); }, + cases: [ + { select: ':required + span', expect: { ids: ['sibling'] } }, + { select: ':not(:optional) + span', expect: { ids: ['sibling'] } }, + ], + }, + ], + }, + + { + name: 'html/semantics/selectors/pseudo-classes/required-optional', + markup: ` + + + + + + + + `, + steps: [ + { + cases: [ + { select: ':required', expect: { ids: ['text1', 'text2', 'select1', 'textarea1'] } }, + { select: ':optional', expect: { ids: ['text3', 'select2', 'textarea2'] } }, + ], + }, + { + setupPage: async (page) => { await page.evaluate(() => { document.getElementById('text1')?.removeAttribute('required'); }); }, + cases: [ + { select: ':required', expect: { ids: ['text2', 'select1', 'textarea1'] } }, + { select: ':optional', expect: { ids: ['text1', 'text3', 'select2', 'textarea2'] } }, + ], + }, + { + setupPage: async (page) => { await page.evaluate(() => { document.getElementById('select2')?.setAttribute('required', 'required'); }); }, + cases: [ + { select: ':required', expect: { ids: ['text2', 'select1', 'select2', 'textarea1'] } }, + { select: ':optional', expect: { ids: ['text1', 'text3', 'textarea2'] } }, + ], + }, + ], + }, + + { + name: 'html/semantics/selectors/pseudo-classes/valid-invalid', + markup: ` + + + + + Selector: pseudo-classes (:valid, :invalid) + + + + + + + + +
      +
      + + +
      +
      +
      + +
      +
      + +
      +
      +
      +
      + +
      +
      + +
      +
      +
      + + +
      +
      + + +
      +
      +
      +
      +
      + +
      +
      + +
      +
      +
      +
      + +
      +
      + +
      +
      +
      +
      +
      + `, + markupMode: 'html-document', + steps: [ + { + cases: [ + { select: '#simpleConstraints :valid', expect: { ids: ['text1'] } }, + { select: '#FormSelection :valid', expect: { ids: ['form1', 'text3'] } }, + { select: '#FieldSetSelection :valid', expect: { ids: ['fieldset1', 'text5'] } }, + { select: '#patternConstraints :valid', expect: { ids: ['text8'] } }, + { select: '#numberConstraints :valid', expect: { ids: ['number2'] } }, + + { select: '#simpleConstraints :invalid', expect: { ids: ['text2'] } }, + { select: '#FormSelection :invalid', expect: { ids: ['form2', 'text4'] } }, + { select: '#FieldSetSelection :invalid', expect: { ids: ['fieldset2', 'text6'] } }, + { select: '#patternConstraints :invalid', expect: { ids: ['text7'] } }, + { select: '#numberConstraints :invalid', expect: { ids: ['number1'] } }, + ], + }, + { + setupPage: async (page) => { await page.evaluate(() => { (document.getElementById('text7') as HTMLInputElement).value = '0BBB'; }); }, + cases: [ + { select: '#patternConstraints :valid', expect: { ids: ['text7', 'text8'] } }, + { select: '#patternConstraints :invalid', expect: { ids: [] } }, + ], + }, + { + setupPage: async (page) => { await page.evaluate(() => { (document.getElementById('text8') as HTMLInputElement).value = 'BBB'; }); }, + cases: [ + { select: '#patternConstraints :valid', expect: { ids: ['text7'] } }, + { select: '#patternConstraints :invalid', expect: { ids: ['text8'] } }, + ], + }, + + { + cases: [ + { select: '#styleTests form:valid', expect: { count: 2 } }, + { select: '#styleTests form:invalid', expect: { count: 1 } }, + ], + }, + { + setupPage: async (page) => { await page.evaluate(() => { + const elems = document.querySelectorAll('#styleTests form'); + const empty = elems[0]; + const valid = elems[1]; + const invalid = elems[2]; + const validInput = valid.querySelector('input')!; + const invalidInput = invalid.querySelector('input')!; + + empty.appendChild(validInput.cloneNode()); + empty.appendChild(invalidInput.cloneNode()); + + (validInput as HTMLInputElement).type = 'number'; + (invalidInput as HTMLInputElement).type = 'text'; + }); }, + cases: [ + { select: '#styleTests form:valid', expect: { count: 1 } }, + { select: '#styleTests form:invalid', expect: { count: 2 } }, + ], + }, + + { + cases: [ + { select: '#styleTests fieldset:valid', expect: { count: 2 }, status: 'fixme' }, + { select: '#styleTests fieldset:invalid', expect: { count: 1 } }, + ], + }, + { + setupPage: async (page) => { await page.evaluate(() => { + const elems = document.querySelectorAll('#styleTests fieldset'); + const empty = elems[0]; + const valid = elems[1]; + const invalid = elems[2]; + const validInput = valid.querySelector('input')!; + const invalidInput = invalid.querySelector('input')!; + + empty.appendChild(validInput.cloneNode()); + empty.appendChild(invalidInput.cloneNode()); + + (validInput as HTMLInputElement).type = 'number'; + (invalidInput as HTMLInputElement).type = 'text'; + }); }, + cases: [ + { select: '#styleTests fieldset:valid', expect: { count: 1 }, status: 'fixme' }, + { select: '#styleTests fieldset:invalid', expect: { count: 2 } }, + ], + }, + ], + }, + + { + name: 'html/syntax/parsing/template/template-is-a-foster-parent-element', + markup: ` +
      + +
      + `, + cases: [ + // foster-parented before the table in template content + { select: '#orphanDiv', expect: { ids: [] } }, + { select: '#orphanDiv', ref: { by: 'template', id: 'tmpl1' }, expect: { ids: ['orphanDiv'] } }, + { select: 'table #orphanDiv', ref: { by: 'template', id: 'tmpl1' }, expect: { ids: [] } }, + { select: '#orphanDiv + table', ref: { by: 'template', id: 'tmpl1' }, expect: { ids: ['tbl'] } }, + ], + }, + + { + name: 'html/syntax/parsing/template/template-is-a-foster-parent-element-without-table', + // status: 'only', + markup: ` +
      + +
      + `, + cases: [ + // without a table, rows and div remain sibling content + { select: '#orphanDiv', expect: { ids: [] } }, + { select: '#orphanDiv', ref: { by: 'template', id: 'tmpl1' }, expect: { ids: ['orphanDiv'] } }, + { select: 'table', ref: { by: 'template', id: 'tmpl1' }, expect: { count: 0 } }, + { select: 'tr', ref: { by: 'template', id: 'tmpl1' }, expect: { count: 2 } }, + { select: 'tr + #orphanDiv', ref: { by: 'template', id: 'tmpl1' }, expect: { ids: ['orphanDiv'] } }, + { select: 'tr ~ #orphanDiv', ref: { by: 'template', id: 'tmpl1' }, expect: { ids: ['orphanDiv'] } }, + ], + }, + + { + name: 'html/syntax/parsing/template/template-is-not-a-foster-parent-element', + markup: ` +
      + +
      + `, + cases: [ + // orphanDiv is foster-parented to fosterParent inside template content + { select: '#orphanDiv', ref: { by: 'template', id: 'tmpl1' }, expect: { ids: ['orphanDiv'] } }, + { select: 'table #orphanDiv', ref: { by: 'template', id: 'tmpl1' }, expect: { ids: [] } }, + { select: '#fosterParent > #orphanDiv', ref: { by: 'template', id: 'tmpl1' }, expect: { ids: ['orphanDiv'] } }, + { select: '#orphanDiv + table', ref: { by: 'template', id: 'tmpl1' }, expect: { ids: ['tbl'] } }, + ], + }, + + { + name: 'html/syntax/parsing/template/template-is-not-a-foster-parent-element-lower-in-stack', + markup: ` +
      + + + +
      Orphan div content
      + +
      Cell 2
      +
      + `, + cases: [ + // normal foster-parenting applies; template does not capture orphanDiv + { select: '#tmpl1', expect: { ids: ['tmpl1'] } }, + { select: '#orphanDiv', expect: { ids: ['orphanDiv'] } }, + { select: 'table #orphanDiv', expect: { ids: [] } }, + { select: '#fosterParent > #orphanDiv', expect: { ids: ['orphanDiv'] } }, + { select: '#orphanDiv + table', expect: { ids: ['tbl'] } }, + ], + }, + + { + name: 'html/syntax/parsing/template/generating-of-implied-end-tags', + markup: `
      `, + steps: [ + { + setupPage: async (page) => { + await page.evaluate(() => { + document.body.innerHTML = ''; + }); + }, + cases: [ + { select: '#tpl', expect: { ids: ['tpl'] } }, + { select: '#tbl', expect: { ids: [] } }, + { select: '#tr', expect: { ids: [] } }, + { select: '#td', expect: { ids: [] } }, + { select: '#tbl', ref: { by: 'template', id: 'tpl' }, expect: { ids: ['tbl'] } }, + { select: '#tr', ref: { by: 'template', id: 'tpl' }, expect: { ids: ['tr'] } }, + { select: '#td', ref: { by: 'template', id: 'tpl' }, expect: { ids: ['td'] } }, + ], + }, + { + setupPage: async (page) => { + await page.evaluate(() => { + document.body.innerHTML = ''; + }); + }, + cases: [ + { select: '#tpl', expect: { ids: ['tpl'] } }, + { select: '#dv', expect: { ids: [] } }, + { select: '#dv', ref: { by: 'template', id: 'tpl' }, expect: { ids: ['dv'] } }, + ], + }, + { + setupPage: async (page) => { + await page.evaluate(() => { + document.body.innerHTML = ''; + }); + }, + cases: [ + { select: '#tpl', expect: { ids: ['tpl'] } }, + { select: '#dv', expect: { ids: [] } }, + { select: '#dv', ref: { by: 'template', id: 'tpl' }, expect: { ids: ['dv'] } }, + ], + }, + { + setupPage: async (page) => { + await page.evaluate(() => { + document.body.innerHTML = ''; + }); + }, + cases: [ + { select: '#tpl', expect: { ids: ['tpl'] } }, + { select: '#dv', expect: { ids: [] } }, + { select: '#dv', ref: { by: 'template', id: 'tpl' }, expect: { ids: ['dv'] } }, + ], + }, + ], + }, + + { + name: 'html/syntax/parsing/template/ignore-body-token', + markup: ` + + `, + steps: [ + { + setupPage: async (page) => { await page.evaluate(() => { + const template = document.getElementById('tpl') as HTMLTemplateElement; + template.innerHTML = ''; + }); }, + cases: [ + { select: 'body', ref: { by: 'template', id: 'tpl' }, expect: { count: 0 } }, + { select: '*', ref: { by: 'template', id: 'tpl' }, expect: { count: 0 } }, + ], + }, + + { + setupPage: async (page) => { await page.evaluate(() => { + const template = document.getElementById('tpl') as HTMLTemplateElement; + template.innerHTML = '
      Some content
      '; + }); }, + cases: [ + { select: 'body', ref: { by: 'template', id: 'tpl' }, expect: { count: 0 } }, + { select: '#div1', ref: { by: 'template', id: 'tpl' }, expect: { ids: ['div1'] } }, + { select: 'div', ref: { by: 'template', id: 'tpl' }, expect: { ids: ['div1'] } }, + ], + }, + + { + setupPage: async (page) => { await page.evaluate(() => { + const template = document.getElementById('tpl') as HTMLTemplateElement; + template.innerHTML = '
      Some content
      Some valid content
      '; + }); }, + cases: [ + { select: 'body', ref: { by: 'template', id: 'tpl' }, expect: { count: 0 } }, + { select: '#div1', ref: { by: 'template', id: 'tpl' }, expect: { ids: ['div1'] } }, + { select: '#div2', ref: { by: 'template', id: 'tpl' }, expect: { ids: ['div2'] } }, + { select: 'div', ref: { by: 'template', id: 'tpl' }, expect: { count: 2 } }, + ], + }, + + { + setupPage: async (page) => { await page.evaluate(() => { + const template = document.getElementById('tpl') as HTMLTemplateElement; + template.innerHTML = '
      Some valid content
      Some content
      '; + }); }, + cases: [ + { select: 'body', ref: { by: 'template', id: 'tpl' }, expect: { count: 0 } }, + { select: '#div1', ref: { by: 'template', id: 'tpl' }, expect: { ids: ['div1'] } }, + { select: '#div2', ref: { by: 'template', id: 'tpl' }, expect: { ids: ['div2'] } }, + { select: 'div', ref: { by: 'template', id: 'tpl' }, expect: { count: 2 } }, + ], + }, + + { + setupPage: async (page) => { await page.evaluate(() => { + const template = document.getElementById('tpl') as HTMLTemplateElement; + template.innerHTML = ''; + }); }, + cases: [ + { select: '#t2', ref: { by: 'template', id: 'tpl' }, expect: { ids: ['t2'] } }, + { select: 'body', ref: { by: 'template', id: 't2', within: { by: 'template', id: 'tpl' } }, expect: { count: 0 } }, + { select: 'span', ref: { by: 'template', id: 't2', within: { by: 'template', id: 'tpl' } }, expect: { count: 2 } }, + ], + }, + ], + }, + + { + name: 'html/syntax/parsing/template/ignore-frameset-token', + markup: ` + + + + + + + + `, + steps: [ + // frameset is ignored inside template content + { + cases: [ + { select: 'frameset', ref: { by: 'template', id: 'tpl-frameset-only' }, expect: { count: 0 } }, + { select: 'frame', ref: { by: 'template', id: 'tpl-frameset-only' }, expect: { count: 0 } }, + { select: '*', ref: { by: 'template', id: 'tpl-frameset-only' }, expect: { count: 0 } }, + ], + }, + + // valid content before frameset survives + { + cases: [ + { select: 'frameset', ref: { by: 'template', id: 'tpl-valid-before-frameset' }, expect: { count: 0 } }, + { select: 'frame', ref: { by: 'template', id: 'tpl-valid-before-frameset' }, expect: { count: 0 } }, + { select: '#div-before', ref: { by: 'template', id: 'tpl-valid-before-frameset' }, expect: { ids: ['div-before'] } }, + { select: 'div', ref: { by: 'template', id: 'tpl-valid-before-frameset' }, expect: { ids: ['div-before'] } }, + { select: '*', ref: { by: 'template', id: 'tpl-valid-before-frameset' }, expect: { count: 1 } }, + ], + }, + + // valid content after frameset survives + { + cases: [ + { select: 'frameset', ref: { by: 'template', id: 'tpl-valid-after-frameset' }, expect: { count: 0 } }, + { select: 'frame', ref: { by: 'template', id: 'tpl-valid-after-frameset' }, expect: { count: 0 } }, + { select: '#div-after', ref: { by: 'template', id: 'tpl-valid-after-frameset' }, expect: { ids: ['div-after'] } }, + { select: 'div', ref: { by: 'template', id: 'tpl-valid-after-frameset' }, expect: { ids: ['div-after'] } }, + ], + }, + + // nested template survives; frameset inside it is ignored + { + cases: [ + { select: '#t2', ref: { by: 'template', id: 'tpl-nested-template' }, expect: { ids: ['t2'] } }, + { select: 'frameset', ref: { by: 'template', id: 't2', within: { by: 'template', id: 'tpl-nested-template' } }, expect: { count: 0 } }, + { select: 'frame', ref: { by: 'template', id: 't2', within: { by: 'template', id: 'tpl-nested-template' } }, expect: { count: 0 } }, + { select: '*', ref: { by: 'template', id: 't2', within: { by: 'template', id: 'tpl-nested-template' } }, expect: { count: 0 } }, + ], + }, + ], + }, + + { + name: 'html/syntax/parsing/template/ignore-head-token', + markup: ` + + + + + + + + + + `, + steps: [ + // empty head is ignored + { + cases: [ + { select: 'head', ref: { by: 'template', id: 'tpl-head-empty' }, expect: { count: 0 } }, + { select: '*', ref: { by: 'template', id: 'tpl-head-empty' }, expect: { count: 0 } }, + ], + }, + + // children of ignored head survive + { + cases: [ + { select: 'head', ref: { by: 'template', id: 'tpl-head-title' }, expect: { count: 0 } }, + { select: 'title', ref: { by: 'template', id: 'tpl-head-title' }, expect: { count: 1 } }, + { select: '*', ref: { by: 'template', id: 'tpl-head-title' }, expect: { count: 1 } }, + ], + }, + + // valid content before head survives + { + cases: [ + { select: 'head', ref: { by: 'template', id: 'tpl-valid-before-head' }, expect: { count: 0 } }, + { select: '#div-before', ref: { by: 'template', id: 'tpl-valid-before-head' }, expect: { ids: ['div-before'] } }, + { select: 'title', ref: { by: 'template', id: 'tpl-valid-before-head' }, expect: { count: 1 } }, + { select: '*', ref: { by: 'template', id: 'tpl-valid-before-head' }, expect: { count: 2 } }, + ], + }, + + // valid content after head survives + { + cases: [ + { select: 'head', ref: { by: 'template', id: 'tpl-head-before-valid' }, expect: { count: 0 } }, + { select: 'title', ref: { by: 'template', id: 'tpl-head-before-valid' }, expect: { count: 1 } }, + { select: '#div-after', ref: { by: 'template', id: 'tpl-head-before-valid' }, expect: { ids: ['div-after'] } }, + { select: '*', ref: { by: 'template', id: 'tpl-head-before-valid' }, expect: { count: 2 } }, + ], + }, + + // nested template survives; head inside it is ignored + { + cases: [ + { select: '#t2', ref: { by: 'template', id: 'tpl-nested-head' }, expect: { ids: ['t2'] } }, + { select: 'head', ref: { by: 'template', id: 't2', within: { by: 'template', id: 'tpl-nested-head' } }, expect: { count: 0 } }, + { select: 'title', ref: { by: 'template', id: 't2', within: { by: 'template', id: 'tpl-nested-head' } }, expect: { count: 1 } }, + { select: '*', ref: { by: 'template', id: 't2', within: { by: 'template', id: 'tpl-nested-head' } }, expect: { count: 1 } }, + ], + }, + ], + }, + + { + name: 'html/syntax/parsing/template/ignore-html-token', + markup: ` + + + + + + + + + + + + + + `, + steps: [ + // empty html/body is ignored + { + cases: [ + { select: 'html', ref: { by: 'template', id: 'tpl-html-empty' }, expect: { count: 0 } }, + { select: 'body', ref: { by: 'template', id: 'tpl-html-empty' }, expect: { count: 0 } }, + { select: '*', ref: { by: 'template', id: 'tpl-html-empty' }, expect: { count: 0 } }, + ], + }, + + // valid content before html survives + { + cases: [ + { select: 'html', ref: { by: 'template', id: 'tpl-valid-before-html' }, expect: { count: 0 } }, + { select: 'body', ref: { by: 'template', id: 'tpl-valid-before-html' }, expect: { count: 0 } }, + { select: '#div-before', ref: { by: 'template', id: 'tpl-valid-before-html' }, expect: { ids: ['div-before'] } }, + { select: '*', ref: { by: 'template', id: 'tpl-valid-before-html' }, expect: { count: 1 } }, + ], + }, + + // valid content after html survives + { + cases: [ + { select: 'html', ref: { by: 'template', id: 'tpl-html-before-valid' }, expect: { count: 0 } }, + { select: 'body', ref: { by: 'template', id: 'tpl-html-before-valid' }, expect: { count: 0 } }, + { select: '#div-after', ref: { by: 'template', id: 'tpl-html-before-valid' }, expect: { ids: ['div-after'] } }, + { select: '*', ref: { by: 'template', id: 'tpl-html-before-valid' }, expect: { count: 1 } }, + ], + }, + + // nested template survives; html/body inside it are ignored + { + cases: [ + { select: '#t2', ref: { by: 'template', id: 'tpl-nested-html' }, expect: { ids: ['t2'] } }, + { select: 'html', ref: { by: 'template', id: 't2', within: { by: 'template', id: 'tpl-nested-html' } }, expect: { count: 0 } }, + { select: 'body', ref: { by: 'template', id: 't2', within: { by: 'template', id: 'tpl-nested-html' } }, expect: { count: 0 } }, + { select: '*', ref: { by: 'template', id: 't2', within: { by: 'template', id: 'tpl-nested-html' } }, expect: { count: 0 } }, + ], + }, + + // valid content inside ignored html survives + { + cases: [ + { select: 'html', ref: { by: 'template', id: 'tpl-valid-inside-html' }, expect: { count: 0 } }, + { select: '#div-inside-html', ref: { by: 'template', id: 'tpl-valid-inside-html' }, expect: { ids: ['div-inside-html'] } }, + { select: '*', ref: { by: 'template', id: 'tpl-valid-inside-html' }, expect: { count: 1 } }, + ], + }, + + // valid content inside ignored html/body survives + { + cases: [ + { select: 'html', ref: { by: 'template', id: 'tpl-valid-inside-html-body' }, expect: { count: 0 } }, + { select: 'body', ref: { by: 'template', id: 'tpl-valid-inside-html-body' }, expect: { count: 0 } }, + { select: '#div-inside-body', ref: { by: 'template', id: 'tpl-valid-inside-html-body' }, expect: { ids: ['div-inside-body'] } }, + { select: '*', ref: { by: 'template', id: 'tpl-valid-inside-html-body' }, expect: { count: 1 } }, + ], + }, + + // valid content both before and inside ignored body survives + { + cases: [ + { select: 'html', ref: { by: 'template', id: 'tpl-valid-between-html-body' }, expect: { count: 0 } }, + { select: 'body', ref: { by: 'template', id: 'tpl-valid-between-html-body' }, expect: { count: 0 } }, + { select: '#span1', ref: { by: 'template', id: 'tpl-valid-between-html-body' }, expect: { ids: ['span1'] } }, + { select: '#div1', ref: { by: 'template', id: 'tpl-valid-between-html-body' }, expect: { ids: ['div1'] } }, + { select: '*', ref: { by: 'template', id: 'tpl-valid-between-html-body' }, expect: { count: 2 } }, + ], + }, + ], + }, + + { + name: 'html/syntax/parsing/template/start-tag-body', + markup: ` + + + + + + + + `, + steps: [ + // bare body tag is ignored + { + cases: [ + { select: 'body', ref: { by: 'template', id: 'tmpl-body-only' }, expect: { count: 0 } }, + { select: '*', ref: { by: 'template', id: 'tmpl-body-only' }, expect: { count: 0 } }, + ], + }, + + // body tag is ignored but its text survives + { + cases: [ + { select: 'body', ref: { by: 'template', id: 'tmpl-body-text' }, expect: { count: 0 } }, + { select: '*', ref: { by: 'template', id: 'tmpl-body-text' }, expect: { count: 0 } }, + ], + }, + + // body tag is ignored but child elements survive + { + cases: [ + { select: 'body', ref: { by: 'template', id: 'tmpl-body-elements' }, expect: { count: 0 } }, + { select: '#div1', ref: { by: 'template', id: 'tmpl-body-elements' }, expect: { ids: ['div1'] } }, + { select: '#div2', ref: { by: 'template', id: 'tmpl-body-elements' }, expect: { ids: ['div2'] } }, + { select: '*', ref: { by: 'template', id: 'tmpl-body-elements' }, expect: { count: 2 } }, + ], + }, + + // nested template: body is ignored inside nested template content too + { + cases: [ + { select: '#tmpl2', ref: { by: 'template', id: 'tmpl-nested-body' }, expect: { ids: ['tmpl2'] } }, + { select: 'body', ref: { by: 'template', id: 'tmpl2', within: { by: 'template', id: 'tmpl-nested-body' } }, expect: { count: 0 } }, + { select: '#nested-div1', ref: { by: 'template', id: 'tmpl2', within: { by: 'template', id: 'tmpl-nested-body' } }, expect: { ids: ['nested-div1'] } }, + { select: '#nested-div2', ref: { by: 'template', id: 'tmpl2', within: { by: 'template', id: 'tmpl-nested-body' } }, expect: { ids: ['nested-div2'] } }, + { select: '*', ref: { by: 'template', id: 'tmpl2', within: { by: 'template', id: 'tmpl-nested-body' } }, expect: { count: 2 } }, + ], + }, + ], + }, + + { + name: 'html/syntax/parsing/template/template-end-tag-without-start-one', + markup: '', + steps: [ + // lone stray is ignored + { + setupPage: async (page) => { await page.evaluate(() => { + document.body.innerHTML = ''; + }); }, + cases: [ + { select: 'body *', expect: { count: 0 } }, + ], + }, + + // stray after a valid template is ignored + { + setupPage: async (page) => { await page.evaluate(() => { + document.body.innerHTML = ''; + }); }, + cases: [ + { select: '#tmpl', expect: { ids: ['tmpl'] } }, + { select: 'body *', expect: { count: 1 } }, + ], + }, + + // stray before a valid template is ignored + { + setupPage: async (page) => { await page.evaluate(() => { + document.body.innerHTML = ''; + }); }, + cases: [ + { select: '#tmpl', expect: { ids: ['tmpl'] } }, + { select: 'body *', expect: { count: 1 } }, + ], + }, + + // stray before valid template and title is ignored + { + setupPage: async (page) => { await page.evaluate(() => { + document.body.innerHTML = ''; + }); }, + cases: [ + { select: '#tmpl', expect: { ids: ['tmpl'] } }, + { select: '#title1', expect: { ids: ['title1'] } }, + { select: 'body *', expect: { count: 2 } }, + ], + }, + + // stray after valid template and title is ignored + { + setupPage: async (page) => { await page.evaluate(() => { + document.body.innerHTML = ''; + }); }, + cases: [ + { select: '#tmpl', expect: { ids: ['tmpl'] } }, + { select: '#title1', expect: { ids: ['title1'] } }, + { select: 'body *', expect: { count: 2 } }, + ], + }, + ], + }, + + { + name: 'jsdom/dom/nodes/documentfragment-getelementbyid', + markup: ` +
      + +
      +
      + +
      + +
      + hello +
      +
      + + + `, + steps: [ + { + cases: [ + { select: '#foo', ref: { by: 'id', id: 'frag-root', home: 'fragment' }, expect: { count: 0 } }, + { byId: 'foo', ref: { by: 'id', id: 'frag-root', home: 'fragment' }, expect: { count: 0 } }, + ], + }, + { + cases: [ + { select: '#foo', ref: { by: 'id', id: 'frag-dupes', home: 'fragment' }, expect: { count: 2 } }, + { byId: 'foo', ref: { by: 'id', id: 'frag-dupes', home: 'fragment' }, expect: { ids: ['foo'] }, status: 'fixme' }, + ], + }, + { + cases: [ + { byId: '', ref: { by: 'id', id: 'frag-empty-id', home: 'fragment' }, expect: { count: 0 }, status: 'fixme' }, + ], + }, + { + cases: [ + { select: '#foo', ref: { by: 'template', id: 'tmpl' }, expect: { count: 4 } }, + { byId: 'foo', ref: { by: 'template', id: 'tmpl' }, expect: { ids: ['foo'], classes: ['first-foo'] }, status: 'fixme' }, + ], + }, + ], + }, + + { + name: 'jsdom/dom/nodes/queryselector', + markup: `
      `, + steps: [ + { + setupPage: async (page) => { await page.evaluate(() => { + document.body.innerHTML = '
      '; + + const host = document.getElementById('host')!; + const g = document.createElement('_g'); + const b = document.createElement('b'); + + b.className = 'hit'; + b.appendChild(document.createTextNode('hey')); + g.appendChild(b); + host.appendChild(g); + }); }, + cases: [ + { select: '_g > b', ref: { by: 'id', id: 'host' }, expect: { count: 1, classes: ['hit'] } }, + { select: '_g > b', ref: { by: 'id', id: 'host', home: 'fragment' }, expect: { count: 1, classes: ['hit'] } }, + ], + }, + ], + }, + + { + name: 'jsdom/dom/nodes/svg-template-query-selector', + markup: ` + + + + `, + cases: [ + { select: 'div', ref: { by: 'template', id: 'template1' }, expect: { count: 1 } }, + { select: 'svg', ref: { by: 'template', id: 'template2' }, expect: { count: 1, classes: ['svg-hit'] } }, + { select: 'svg', ref: { by: 'id', id: 'wrap', within: { by: 'template', id: 'template3' } }, expect: { count: 1, classes: ['nested-svg-hit'] } }, + { select: 'div > svg', ref: { by: 'template', id: 'template3' }, expect: { count: 1, classes: ['nested-svg-hit'] } }, + ], + }, + + { + name: 'jsdom/svg/element-svg', + markup: ` + + + + + `, + steps: [ + { + cases: [ + { select: '#group', expect: { ids: ['group'] } }, + { select: '#group', ref: { by: 'first', selector: 'svg' }, expect: { count: 1 } }, + { select: ':scope > *', ref: { by: 'first', selector: 'svg' }, expect: { count: 1 }, status: 'fixme' }, + { select: '#group', ref: { by: 'first', selector: 'svg' }, expect: { equivalentCase: { first: ':scope > *', ref: { by: 'first', selector: 'svg' } } }, status: 'fixme' }, + { select: '#group', expect: { equivalentCase: { first: '#first > *'} } }, + ], + }, + ], + }, + + +]); + + + + + + + + + diff --git a/test_new/browser/xml.test.ts b/test_new/browser/xml.test.ts new file mode 100644 index 0000000..87cb044 --- /dev/null +++ b/test_new/browser/xml.test.ts @@ -0,0 +1,107 @@ +// import { expect } from "@playwright/test"; +import { runScenarios } from "./harness/scenarios"; + +runScenarios('xml', 'normal', [ + { + name: 'jsdom/svg-test', + markup: ` + + + `, + markupMode: 'html-document', + cases: [ + { select: '[*|href]', expect: { count: 1 } }, + { select: '[xlink:href=foo]', expect: { count: 1 }, status: 'fixme' }, + { select: '[xlink\\:href=foo]', expect: { count: 1 }, status: 'fixme' }, + ], + }, + + { + name: 'jsdom/xml-import-test', + markup: `
      `, + setupPage: async (page) => { await page.evaluate(() => { + const parser = new DOMParser(); + const xml = ` + + + `; + const dom = parser.parseFromString(xml, 'text/xml'); + document.getElementById('host')!.appendChild(document.importNode(dom.documentElement, true)); + }); }, + cases: [ + { select: 'coreProperties', ref: { by: 'id', id: 'host' }, expect: { count: 1 }, status: 'fixme' }, + { select: '*|coreProperties', ref: { by: 'id', id: 'host' }, expect: { count: 1 }, status: 'fixme' }, + { select: '|coreProperties', ref: { by: 'id', id: 'host' }, expect: { count: 0 }, status: 'fixme' }, + ], + }, + + { + name: 'jsdom/xml-markup-mode', + markup: ` + + + `, + markupMode: 'xml-document', + cases: [ + { select: 'coreProperties', expect: { count: 1 }, status: 'fixme' }, + { select: '*|coreProperties', expect: { count: 1 }, status: 'fixme' }, + { select: '|coreProperties', expect: { count: 0 }, status: 'fixme' }, + ], + }, + + { + name: 'xml-import-case-insensitivity', + markup: `
      `, + setupPage: async (page) => { + await page.evaluate(() => { + const xml = ``; + const dom = new DOMParser().parseFromString(xml, 'text/xml'); + document.getElementById('host')!.appendChild( + document.importNode(dom.documentElement, true) + ); + }); + }, + cases: [ + { select: 'Foo', ref: { by: 'id', id: 'host' }, expect: { count: 1 } }, + { select: 'foo', ref: { by: 'id', id: 'host' }, expect: { count: 0 }, status: 'fixme' }, + { select: 'bar', ref: { by: 'id', id: 'host' }, expect: { count: 1 } }, + { select: 'Bar', ref: { by: 'id', id: 'host' }, expect: { count: 0 }, status: 'fixme' }, + ], + }, + + { + name: 'xml-markup-mode-case-sensitivity', + markupMode: 'xml-document', + markup: ` + + + + + + + + `, + cases: [ + // upper: + { select: 'Foo', ref: { by: 'id', id: 'upper' }, expect: { count: 1 } }, + { select: 'foo', ref: { by: 'id', id: 'upper' }, expect: { count: 0 } }, + { select: 'bar', ref: { by: 'id', id: 'upper' }, expect: { count: 1 } }, + { select: 'Foo bar', ref: { by: 'id', id: 'upper' }, expect: { count: 1 } }, + { select: 'foo bar', ref: { by: 'id', id: 'upper' }, expect: { count: 0 } }, + + // lower: + { select: 'foo', ref: { by: 'id', id: 'lower' }, expect: { count: 1 } }, + { select: 'Foo', ref: { by: 'id', id: 'lower' }, expect: { count: 0 } }, + { select: 'bar', ref: { by: 'id', id: 'lower' }, expect: { count: 1 } }, + { select: 'Bar', ref: { by: 'id', id: 'lower' }, expect: { count: 0 } }, + { select: '#lower foo bar', expect: { count: 1 } }, + { select: '#lower Foo bar', expect: { count: 0 } }, + { select: '#lower FOO bar', expect: { count: 0 } }, + { select: '#lower foo BAR', expect: { count: 0 } }, + { select: '#lower FOO BAR', expect: { count: 0 } }, + ], + }, + +]); diff --git a/test_new/global.d.ts b/test_new/global.d.ts new file mode 100644 index 0000000..3b50ea1 --- /dev/null +++ b/test_new/global.d.ts @@ -0,0 +1,29 @@ +import type { PwHelpers } from './browser/harness/browser'; + +export {}; + +declare global { + type QueryContext = Document | Element | DocumentFragment; + type NwCallback = (element: Element) => boolean | void; + + interface Window { + __pwHelpers: PwHelpers; + __pwXml: XMLDocument; + __pwArg: unknown; + } + + const NW: { + Dom: { + byId(id: string, ctx: QueryContext): Element[]; + byTag(tag: string, ctx: QueryContext): Element[]; + byClass(cls: string, ctx: QueryContext): Element[]; + + select(selector: string, ctx?: QueryContext | null, callback?: NwCallback | null): Element[]; + first(selector: string, ctx?: QueryContext | null, callback?: NwCallback | null): Element | null; + match(selector: string, ctx?: Element | null, callback?: NwCallback | null): boolean; + closest(selector: string, ctx: Element, callback?: NwCallback | null): Element | null; + + configure(options: Record): void; + }; + }; +} \ No newline at end of file diff --git a/test_new/tsconfig.json b/test_new/tsconfig.json new file mode 100644 index 0000000..7371cd6 --- /dev/null +++ b/test_new/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "es2020", + "module": "nodenext", + "moduleResolution": "nodenext", + "strict": true, + "noEmit": true, + "lib": ["esnext", "DOM"], + "types": ["node"] + }, + "include": ["./**/*.ts"] +} \ No newline at end of file diff --git a/test_new/utils/type.ts b/test_new/utils/type.ts new file mode 100644 index 0000000..257a837 --- /dev/null +++ b/test_new/utils/type.ts @@ -0,0 +1,9 @@ +export type DistributiveOmit = T extends unknown ? Omit : never; + +export function assertNever(x: never): never { + throw new Error(`Unexpected key: ${x}`); +} + +export type Permutations = + [T] extends [never] ? [] : + T extends K ? [T, ...Permutations>] : never;