📜 ⬆️ ⬇️

CSS3 search


Many are probably familiar with the quicksearch plugin for jQuery. This plugin, sorting through a pre-prepared list of all elements and their textual representation, checks for the presence of keywords using the indexOf function.

I did not like this decision. I believe that this functionality should be native.



It seems that the pseudo-class : contains () was intended for this, but the UFO flew in and published the following in the standard:
6.6.6. Blank
This section intentionally left blank. (This section was previously defined a: contains () pseudo-class.)

I found an alternative: attribute selector [att * = val] . It allows you to make a selection of elements with an attribute containing a substring (which, in fact, is analogous to indexOf). Thus, by dynamically adding and deleting styles, we can do a search almost entirely on CSS and only the control logic will be on javascript. To do this, we need to create in advance the attributes containing the textual representation of the elements. This can be done on the server, or you can use javascript on the client.
')
An example of the implementation of this method

if (!document.head) document.head = document.getElementsByTagName('head')[0]; var css = document.createElement("style"); document.head.appendChild(css); function search() { var selector = ''; var searchBox = document.getElementById('searchBox'); var keywords = searchBox.value.toLowerCase().split(' ').filter(Boolean); for (var i = 0; i < keywords.length; i++) selector += (i ? ',' : '') + 'div:not([index*="' + keywords[i] + '"])'; if (selector) css.innerHTML = selector + '{display: none;}'; else css.innerHTML = ""; } $(document).ready(function() { $('div').each(function(key, value) { $(value).attr('index', $(this).text().toLowerCase()); }); $("#searchBox").keyup(search); }); 

Live demo

This selector is supported in all modern browsers (Firefox 3+, Opera 9.5+, IE 7+).
WebKit browsers also support this selector, but due to performance issues on operations with adding and removing styles, it will be difficult to use this technique.

[07.06.2012] Update:
I found some time and conducted an audit of my old projects.
Updated Live demo. Now there is a comparison of search on CSS3 and JavaScript (QuickSearch).
Thanks ivan386 for a very useful comment, thanks to him it is possible to measure the speed correctly.

Back to back comparison

PS: Apparently both options work approximately equally in speed, which was to be expected.

Source: https://habr.com/ru/post/136137/


All Articles