querySelector

by Lee Cooper

HTML

<div>
<p>
<a></a>
</p>
<a></a>
</div>

JavaScript

/**
 * Querys the DOM using querySelectorAll and loops through firing the callback for each iteration. If returning "false" from the function the loop is exited
 * @name queryAll
 * @function
 * @param {string} selector
 * @param {Function} callback
 */
/**
 * Querys the DOM using querySelectorAll and loops through firing the callback for each iteration. If returning "false" from the function the loop is exited
  * @name queryAll^2
  * @function
  * @param {string} element
  * @param {string} selector
  * @param {Function} callback
 */
function queryAll() {

	if(typeof arguments[0] === 'string' || arguments[0] instanceof String){
		return _queryAll(document, arguments[0], arguments[1]);  	
  }
  
  return _queryAll(arguments[0], arguments[1], arguments[2]);  
}

function _queryAll(element, selector, callback) {

	let list = element.querySelectorAll(selector);

  for(let i = 0; i < list.length; i++) {
  	if(callback(list[i], i) === false) {
    	return list;
    }
  }
  
  return list;
}

queryAll('a', (e, i) => console.log(e, i));
queryAll(document.querySelector('p'), 'a', (e, i) => console.log(e, i));