Skip to content

yuxuan-ji/domql

Repository files navigation

Codacy Badge Known Vulnerabilities MIT Licence Size

Tired of using document.querySelector() with CSS selectors? Ever wanted to use SQL-like syntax to query DOM elements?
Yeah, me neither.

Installation & Usage

ES6:

import * as domql from './domql.min.js';
var result = domql.$("SELECT * FROM html WHERE id='foo'");

From script:

<script src="https://cdn.jsdelivr.net/gh/yuxuan-ji/domql@master/dist/domql.min.js"></script>

<script>
    var result = domql.$("SELECT * FROM html WHERE id='foo'");
</script>

Query Syntax

When writing queries, use the following DOMQL query syntax:

SELECT [HTMLTag,...|*] FROM [HTMLTag|*] (WHERE [HTMLTag].[attribute='value'] (, AND|OR ...)) (LIMIT value)

Demo

A demo is available in the Demo Page.

More examples

For even more examples and usage, please refer to the Examples Page.

Compiling a DOMQL query for subsequent usage

You can use the $$ helper method to avoid recompiling the same query:

var cursor = domql.$$("SELECT * FROM html WHERE id='foo'");
// You can then use this cursor for subsequent queries:
var result = cursor.execute();
var result2 = cursor.execute();
...
var resultX = cursor.execute();

Using a different query engine

By default, Domql uses document.querySelectorAll as its query engine. While this results in an overall smaller build file, the default engine has limited support for complex CSS selectors. When you need access to complex queries, it is recommended to use an external query engine such as Sizzle.js like so:

ES6:

import * as Sizzle from './sizzle.min.js';
...
domql.QueryEngine.setEngine(Sizzle.default);

From script:

<script src="https://cdnjs.cloudflare.com/ajax/libs/sizzle/2.3.3/sizzle.min.js"></script>
...
<script>
    domql.QueryEngine.setEngine(Sizzle);
</script>

Development setup

Install Dependencies:

npm install

Build dist:

npm run build

Build JSDoc to markdown documentation:

npm run build:docs

Run tests:

npm run test

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

  1. Fork this repo
  2. Create your feature branch (git checkout -b feature/fooBar)
  3. Commit your changes (git commit -am 'Add some fooBar')
  4. Push to the branch (git push origin feature/fooBar)
  5. Create a new Pull Request