function prev(el, selector) {
if (el instanceof HTMLElement) {
el = el.previousElementSibling;
return el && (!selector || el.matches(selector)) ? el : null;
}
if (el && Number.isInteger(el.length) && el.length >= 0) {
return Array.prototype.reduce.call(
el,
(acc, n) => ((n = prev(n, selector)) && acc.push(n), acc),
[]
);
}
return null;
}
// можно передавать как одиночный элемент (результатом будет тоже элемент или null)...
prev(document.body)
// ... так и коллекции (результатом будет массив)
prev(document.images)
prev(document.querySelectorAll('div'), 'span')
А вообще - загляните-ка
сюда.