element-collector
v2.4.2
Published
HTMLCollection on steroids.
Downloads
11
Readme
Element collector
HTML Collection on steroids.
How to use
var my_collector = new ElementCollector;
// add elements by CSS selector
my_collector.add('.testElements');
// add specific element
my_collector.add(document.getElementById('#testElement'));
// add elements by live HTML Collection
my_collector.add(document.querySelectorAll('div'));
// add elements by callback function
function getElementByUserStatus() {
if (user_exists) {
return document.getElementById('userInfo');
} else {
return document.getElementById('userLogin');
}
}
my_collector.add(getElementByUserStatus);
// get list of all matching elements
my_collector.get();
Constructor
new ElementCollector();
Creates instance of ElementCollector
object. You can then use various methods to work with it.
Methods
add(item)
Adds new item to the list. You can add any of various types of items. Does not add duplicates if item already exists in the list.
my_collector.add('.testElements'); // CSS selector
my_collector.add(document.getElementById('#testElement')); // element
my_collector.add(document.querySelectorAll('div')); // collection
my_collector.add(getElementByUserStatus); // function
remove(item)
Removes item from the list. Does nothing if item is not in the list.
my_collector.remove('.testElements');
my_collector.remove(document.getElementById('#testElement'));
my_collector.remove(document.querySelectorAll('div'));
my_collector.remove(getElementByUserStatus);
reset()
Removes all items from the list.
get(root_node)
Returns array of all elements matching all added items. The result contains only unique elements. For example, if collector contains two CSS selectors, each returning the same elements, the result will only contain each element once.
root_node
is document.body
by default. You can use any other node, even the ones that are not added to document.body
yet (e.g. fragments). If the root_node
does not exist, returns an empty array.
Item types
- CSS selector - non-empty string
- element reference - any reference to an existing element
- elements enumerable - array (e.g.
document.getElementsByTagName
) or collection (e.g.document.querySelectorAll
) of elements - function - any function that returns single element or elements enumerable
Documentation
Bug reports, feature requests and contact
If you found any bugs, if you have feature requests or any questions, please, either file an issue at GitHub or send me an e-mail at mailto:[email protected].
License
Element collector is published under the MIT license.